简体   繁体   English

准备好的语句共享连接

[英]prepared statements sharing connection

There is an example that shows using transactions: 有一个示例显示使用事务:

con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
...
con.commit();
...
finally
updateSales close
updateTotal close

If I wanted to move two prepared statements into separate methods sharing a connection/transaction, each called from a parent method, I do not see how to handle closing the prepared statements, since the parent method would open the connection and then commit it. 如果我想将两个准备好的语句移到共享一个连接/事务的单独方法中,每个方法都从父方法调用,则我看不到如何处理关闭准备好的语句,因为父方法会先打开连接然后再提交。

parentmethod:
con.setAutoCommit(false)
method1(con)
method2(con)
con.commit()

Do not need to engineer it as such. 无需照此设计。 Just felt logical to separate out the updates. 感觉很合理,可以分开更新。

Why not have the PreparedStatement 's scope set to the class level? 为什么不将PreparedStatement的范围设置为类级别? The parent method could then have a finally block that closes all resources that the child methods may have opened. 然后,父方法可以有一个finally块,该块关闭子方法可能已经打开的所有资源。

This still isn't the best solution (generally you'd want the same method that opened a resource to close the resource). 这仍然不是最佳解决方案(通常,您希望使用与打开资源相同的方法来关闭资源)。

The elegant way, in my opinion, is to keep the PreparedStatement calls at the parent level, alongside other resources. 我认为,一种优雅的方法是将PreparedStatement调用与其他资源一起保留在父级。

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

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