Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
conn = geting the connection object ( using DriverManager.getConnection() method or using connection pool)
stmt = conn.createStatement ("select ...");
// some other logic here
}
catch (SQLException e)
{
// handling the exceptions
}
finally
{
}
这里我的问题是在以下情况下关闭连接对象会出现什么问题。
假设如果没有发生异常,在 try block 那里它会自动关闭连接对象。
try { // same above code stmt.close(); conn.close(); } catch(Exception ex) { // handling the exceptions } finally { }
如果发生某些异常,它将转到catch block ,在那里它会自动关闭连接对象。
try { // same above code } catch(Exception ex) { // handling the exceptions stmt.close(); conn.close(); } finally { }
在finally block 中关闭连接对象。
try { // same above code } catch(Exception ex) { // handling the exceptions } finally { stmt.close(); conn.close(); }
- 使用 close() 方法关闭连接对象与使用 close() 关闭池连接之间的区别。
注意:请不要说在 finally block 中关闭连接对象是好的。我知道那个。如果我在try block 中保持close连接,catch block 有什么问题请说明。
最佳答案
建议在 finally
block 中关闭连接,因为如果你有多个 catch
block (你应该:你应该从不 catch generic Exception
) 你将不必重新编写关闭语句。
finally
block 将总是 在try
之后执行,无论发生什么。因此,如果您遇到 NullPointerException
或您未处理的其他异常,使用 finally
block 可以确保您的资源已正确关闭。
但如果您使用的是 Java 7,我建议您使用 try-with-resources block
关于java - 为什么 JDBC 连接需要在 finally block 中关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816875/