Spring-Jdbc模板和Prepared语句

时间:2014-12-31 07:42:57

标签: java prepared-statement spring-jdbc

使用Spring-Jdbc模板时,是否需要关闭Prepared Statement和Connection(jt.getDataSource()。getConnection())?或者它们将被Template mechanizm关闭?

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);

    }

3 个答案:

答案 0 :(得分:1)

默认情况下,如果您只使用.update(String sql,Object ... args)表单,则JDBCTemplate会在内部执行自己的PreparedStatement。 Spring和您的数据库将为您管理编译的查询,因此您不必担心打开,关闭,资源保护等。

答案 1 :(得分:0)

如果要使用PreparedStatementCreator,而不是调用以SQL语句作为参数的JdbcTemplate方法,则应使用JdbcTemplate方法来获取PreparedStatementCreator作为参数。

在您的示例中,删除:

PreparedStatement updateIgnor = creator.createPreparedStatement(jt.getDataSource().getConnection());
int k = updateIgnor.executeUpdate();

并将其替换为:

int k = jt.update(creator);

这样JdbcTemplate将处理语句和连接资源以及任何事务管理,并根据需要关闭资源。

答案 2 :(得分:0)

使用spring JDBC Template,您不需要关闭或打开连接。它将在内部处理和例外。

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);