简体   繁体   English

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

[英]Spring-Jdbc Template and Prepared statement

Do I need to close Prepared Statement and Connection (jt.getDataSource().getConnection()) when using Spring-Jdbc Template? 使用Spring-Jdbc模板时,我是否需要关闭Prepared Statement and Connection(jt.getDataSource()。getConnection())? Or they will be closed by Template mechanizm? 否则它们将被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);

    }

By default, the JDBCTemplate does its own PreparedStatement internally, if you just use the .update(String sql, Object ... args) form. 默认情况下,如果仅使用.update(String sql,Object ... args)形式,则JDBCTemplate在内部执行其自己的PreparedStatement。 Spring, and your database, will manage the compiled query for you, so you don't have to worry about opening, closing, resource protection, etc. Spring和您的数据库将为您管理已编译的查询,因此您不必担心打开,关闭,资源保护等问题。

If you want to use the PreparedStatementCreator , instead of calling the JdbcTemplate methods that take an SQL statement as a parameter, you should use the JdbcTemplate method that takes your PreparedStatementCreator as a parameter. 如果你想使用PreparedStatementCreator ,而不是调用JdbcTemplate是采取一个SQL语句作为参数的方法,你应该使用JdbcTemplate方法是把你的PreparedStatementCreator作为参数。

In your example remove: 在您的示例中删除:

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

and replace it with: 并替换为:

int k = jt.update(creator);

That way the JdbcTemplate will handle the statement and connection resources plus any transaction management and close the resources as needed. 这样, JdbcTemplate将处理语句和连接资源以及任何事务管理,并根据需要关闭资源。

Using spring JDBC Template you don't need to close or open connections. 使用spring JDBC模板,您无需关闭或打开连接。 it will handle and exceptions internally. 它将在内部处理和异常。

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