首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring-Jdbc模板和预准备语句

Spring-Jdbc模板和预准备语句
EN

Stack Overflow用户
提问于 2014-12-31 15:42:57
回答 3查看 13.3K关注 0票数 2

在使用Spring-Jdbc模板时,我需要关闭准备好的语句和连接(jt.getDataSource().getConnection())吗?或者它们将被模板机制关闭?

代码语言:javascript
复制
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);

    }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-12-31 15:53:11

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

票数 3
EN

Stack Overflow用户

发布于 2015-01-03 01:58:55

如果您想使用PreparedStatementCreator,而不是调用接受SQL语句作为参数的JdbcTemplate方法,则应该使用接受PreparedStatementCreator作为参数的JdbcTemplate方法。

在您的示例中,删除:

代码语言:javascript
复制
PreparedStatement updateIgnor = creator.createPreparedStatement(jt.getDataSource().getConnection());
int k = updateIgnor.executeUpdate();

并将其替换为:

代码语言:javascript
复制
int k = jt.update(creator);

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

票数 0
EN

Stack Overflow用户

发布于 2015-07-22 20:58:23

使用spring JDBC模板,您不需要关闭或打开连接。它将在内部处理和异常。

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27717906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档