在使用Spring-Jdbc模板时,我需要关闭准备好的语句和连接(jt.getDataSource().getConnection())吗?或者它们将被模板机制关闭?
public void updateRow() throws SQLException {
final int i = 100;
final int y = 2;
PreparedStatementCreator creator = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement updateSales = con.prepareStatement(
"update ignor set ignored_id=? where id=?");
updateSales.setInt(1, i);
updateSales.setInt(2, y);
return updateSales;
}
};
PreparedStatement updateIgnor = creator.createPreparedStatement(jt.getDataSource().getConnection());
int k = updateIgnor.executeUpdate();
System.out.println("rows updated = " + k);
}发布于 2014-12-31 15:53:11
缺省情况下,如果只使用.update(String sql,Object ... ),JDBCTemplate会在内部执行自己的PreparedStatement。args)表单。Spring和您的数据库将为您管理已编译的查询,因此您不必担心打开、关闭、资源保护等问题。
发布于 2015-01-03 01:58:55
如果您想使用PreparedStatementCreator,而不是调用接受SQL语句作为参数的JdbcTemplate方法,则应该使用接受PreparedStatementCreator作为参数的JdbcTemplate方法。
在您的示例中,删除:
PreparedStatement updateIgnor = creator.createPreparedStatement(jt.getDataSource().getConnection());
int k = updateIgnor.executeUpdate();并将其替换为:
int k = jt.update(creator);这样,JdbcTemplate将处理语句和连接资源以及任何事务管理,并根据需要关闭资源。
发布于 2015-07-22 20:58:23
使用spring JDBC模板,您不需要关闭或打开连接。它将在内部处理和异常。
Object[] parameters={boolean_value,date_value,int_value};
int[] types={Types.BOOLEAN,Types.TIMESTAMP,Types.INTEGER};
rowsAffected=jdbcTemplate.update("insert into table(col1,col2,col3) values(?,?,?)",parameters,types);https://stackoverflow.com/questions/27717906
复制相似问题