如何使用 try 和资源来让准备好的语句出现异常

问题描述 投票:0回答:1

编写代码以在数据库中插入批次详细信息,但出现以下错误

org.apache.commons.dbcp2.DelegatingPreparedStatement with address: "NULL" is closed.; nested exception is java.sql.SQLException: org.apache.commons.dbcp2.DelegatingPreparedStatement with address: "NULL" is closed.

代码参考

getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            try(PreparedStatement ps = connection.prepareStatement(INSERT_BATCH, new String[] { "batch_id" })) {
                int index = 1;
                ps.setString(index++, batch.getBatchType());
                ps.setTimestamp(index++, getSQLDateTime(batch.getStartedOn()));
                ps.setString(index++, batch.getStatus());
                ps.setString(index++, batch.getHostName());

                return ps;
            }
        }
    }, keyHolder);

此资源尝试是否导致问题并在 JDBC 模板使用连接之前关闭连接?

java postgresql jdbc spring-jdbc apache-commons
1个回答
0
投票

这里不能使用try-with-resources,getJdbcTemplate().update() API应该负责关闭连接

© www.soinside.com 2019 - 2024. All rights reserved.