JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
// final String sql = "INSERT INTO t_user(user_name) VALUES (?)";
Integer count = (Integer) jdbcTemplate.execute(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
return conn.prepareStatement("select 1 from dual");
}
}, new PreparedStatementCallback() {
public Integer doInPreparedStatement(PreparedStatement pstmt) throws SQLException, DataAccessException {
pstmt.execute();
ResultSet rs = pstmt.getResultSet();
rs.next();
return rs.getInt(1);
}
});
int vehicleCount = (Integer) jdbcTemplate.execute("select count(*) from vehicle",new PreparedStatementCallback() {
public Integer doInPreparedStatement(PreparedStatement pstmt) throws SQLException, DataAccessException {
pstmt.execute();
ResultSet rs = pstmt.getResultSet();
rs.next();
return rs.getInt(1);
}
});
本文通过示例展示了如何利用Spring JdbcTemplate执行简单的SQL查询并获取结果集的方法。其中包括了如何通过execute方法配合PreparedStatementCreator及PreparedStatementCallback来完成对数据库的操作。
2016

被折叠的 条评论
为什么被折叠?



