gpt4 book ai didi

java - JDBCTemplate 执行查询后关闭准备好的语句

转载 作者:行者123 更新时间:2023-12-01 20:19:13 27 4
gpt4 key购买 nike

我想在完成数据库查询后关闭我的连接。问题是我正在使用准备好的语句,因为它们是预编译的,所以更安全。我想关闭数据库连接,以便稍后可以将其重新用于另一个查询。

文档内容如下:

/**
* Create a statement in this connection. Allows implementations to use
* PreparedStatements. The JdbcTemplate will close the created statement.
* @param con the connection used to create statement
* @return a prepared statement
* @throws SQLException there is no need to catch SQLExceptions
* that may be thrown in the implementation of this method.
* The JdbcTemplate class will handle them.
*/
PreparedStatement createPreparedStatement(Connection con) throws SQLException;

我遇到了池中没有可用连接的情况。

我有以下内容,但它抛出一个异常,表示语句关闭后不允许进行任何操作。

private IRespondent InsertRespondentToken(IRespondent respondent) {
try{
final String insertRespondent = "insert into respondents_token (SynchroID,TerminalID,QuestionnaireID,ProjectID,Token) values (?,?,?,?,?)";

KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
(Connection con) -> {
try{
PreparedStatement pst = con.prepareStatement(insertRespondent, new String[] {"ID"});
pst.setInt(1, respondent.getSynchroId());
pst.setInt(2, respondent.getTerminalId());

pst.setInt(3, respondent.getQuestionnaireId());

pst.setInt(4,respondent.getProjectId());

respondent.setToken(GenerateUniqueId.getIdentifier());

pst.setString(5,respondent.getToken());

return pst;
}
catch (SQLException e)
{
log.error("Prepared statement failed! Read the stack!",e);
}
finally {
con.close(); // IS thsi right. Or there is another way of doing it.
}
return null;
}
,keyHolder);
}catch(NullPointerException ex){
log.error("Error during end element parsing.", ex);
if (respondent.getId() != -1)
deleteRespondent(respondent.getId());
return null;
}

return respondent;
}

最佳答案

您将关闭连接,并扩展您创建的准备好的语句。因此,当 JdbcTemplate 继续执行该语句时,连接(和语句)已经关闭。您需要删除代码周围的 try-catch-finally 来关闭连接(并吞掉任何异常)。

另请参阅 Spring 文档中 Retrieving Auto-generated Keys 部分的示例。您所需要做的就是准备语句并填充其参数。

看待这个问题的另一种方式是使用资源管理的基本“规则”:您只关闭您创建的内容(除非另有说明)。在这种情况下,您没有创建连接,因此您不负责关闭它。

关于java - JDBCTemplate 执行查询后关闭准备好的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com