这只是一个 java 程序员的愚蠢问题。 我有类似的东西
PreparedStatement stmt = DBConnection.getConnection()
.prepareStatement(sql);
现在在finally block 中我检查stmt是否存在然后关闭它。在这种情况下,Connection
对象会发生什么情况。我知道如果我写在单独的行中,那么我可以关闭它,因为我有一个对连接对象的引用,而在本例中我没有。
最佳答案
What will happen to
Connection
object in this case.
什么都没有。没有什么魔法,所以连接不会神奇地关闭,只是因为您没有将其分配给变量。
这就是为什么您为Connection
使用单独的变量:这样您就可以调用close()
!或者使用 try-with-resources:
try (Connection connection = DBConnection.getConnection()) {
PreparedStatement stmt = connection.prepareStatement(sql);
}
关于java - 在 Java 中关闭数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24472846/