繁体   English   中英

Spring-Jdbc模板和准备好的语句

[英]Spring-Jdbc Template and Prepared statement

使用Spring-Jdbc模板时,我是否需要关闭Prepared Statement and Connection(jt.getDataSource()。getConnection())? 否则它们将被Template机械化关闭?

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

    }

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

如果你想使用PreparedStatementCreator ,而不是调用JdbcTemplate是采取一个SQL语句作为参数的方法,你应该使用JdbcTemplate方法是把你的PreparedStatementCreator作为参数。

在您的示例中删除:

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

并替换为:

int k = jt.update(creator);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM