如果我有以下方法-
public static void C() {
Connection con = DriverManager.getConnection();
.... // code
return;
}
而且我不调用 con.close()
,方法返回后连接会自动终止吗?
最佳答案
...will the connection terminate automatically once the method returns?
不,不会。它最终可能会或可能不会关闭,但如果有的话,还需要很长时间。如果连接打开,连接类的终结器可能会关闭连接,但在很多情况下终结器永远不会运行。显式调用 con.close()
是必要的。
这是我通常处理它的方式(尽管我已经将很多这种逻辑考虑到助手中,因为否则会很冗长):
public static void C()
throws SQLException
{
Connection con = DriverManager.getConnection();
try {
.... // code
// done with the connection
con.close();
con = null;
}
finally {
if (con != null) {
try {
con.close();
}
catch (Exception e) {
// Eat it to avoid masking any exception that
// got us here
}
}
}
}
请注意,在 finally
子句中检测到未关闭的连接后,我将其关闭但不允许任何异常,这样做可能会导致抛出。这是因为主要逻辑正确地关闭了连接,这意味着如果我在 finally
block 中发现了一个打开的连接,则异常已经被抛出并且我们正在处理它,所以我不会我想通过从 con.close()
中抛出一个不同的异常来掩盖这一点。
有了像样的助手,写起来会更短也更容易:
public static void C()
throws SQLException
{
Connection con = DriverManager.getConnection();
try {
.... // code
// done with the connection
con = JDBCHelper.close(con); // <== This one *allows* any exception that occurs
}
finally {
con = JDBCHelper.quietClose(con); // <== This one *eats* any exception that occurs
}
}
...其中 JDBCHelper(一个假设的类)包含:
public static final Connection close(Connection con)
throws SQLException
{
con.close();
return null;
}
public static final Connection quietClose(Connection con)
{
if (con != null) {
try {
con.close();
}
catch (Exception e) {
}
}
return null;
}
关于java - JDBC:如果我失去对 Connection 对象的引用,连接会中断吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983685/