我应该先关闭哪个,PreparedStatement 还是 Connection?
在 JDBC 中使用 PreparedStatement
时,应该先关闭 PreparedStatement
还是先关闭 Connection
?我刚刚看到一个代码示例,其中首先关闭 Connection
,但在我看来,首先关闭 PreparedStatement
更符合逻辑。
是否有一个标准的、可接受的方法来做到这一点?有关系吗?关闭 Connection
是否也会导致 PreparedStatement
关闭,因为 PreparedStatement
与 Connection
对象直接相关?
When using a PreparedStatement
in JDBC, should I close the PreparedStatement
first or the Connection
first? I just saw a code sample in which the Connection
is closed first, but it seems to me more logical to close the PreparedStatement
first.
Is there a standard, accepted way to do this? Does it matter? Does closing the Connection
also cause the PreparedStatement
to be closed, since the PreparedStatement
is directly related to the Connection
object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
声明。我希望您(按顺序)关闭
(并沿途检查空值!)
,即以与打开顺序相反的顺序关闭。
如果您使用 Spring JdbcTemplate (或类似的)那么它将为您处理这个问题。或者,您可以使用 Apache Commons DbUtils 和
DbUtils.close()
或 < a href="http://commons.apache.org/dbutils/apidocs/org/apache/commons/dbutils/DbUtils.html#closeQuietly(java.sql.Connection,%20java.sql.Statement,%20java.sql. ResultSet)" rel="noreferrer">DbUtils.closeQuietly()
。The statement. I would expect you to close (in order)
(and check for nulls along the way!)
i.e. close in reverse order to the opening sequence.
If you use Spring JdbcTemplate (or similar) then that will look after this for you. Alternatively you can use Apache Commons DbUtils and
DbUtils.close()
orDbUtils.closeQuietly()
.应完成以下过程(按顺序)
ResultSet
PreparedStatement
Connection
。另外,建议在
finally
close 中关闭所有 JDBC 相关对象以保证关闭。您可以看到我已经检查了我的对象是否为空,对于连接,如果连接不是自动提交的,请首先检查。许多人没有检查它并意识到事务尚未提交到数据库。
The following procedures should be done (in order)
ResultSet
PreparedStatement
Connection
.Also, it's advisable to close all JDBC related objects in the
finally
close to guarantee closure.You can see I've checked if my objects are null and for connection, check first if the connection is not autocommited. Many people fail to check it and realise that the transaction hasn't been committed to DB.