…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块中找到了打开的连接,则已经引发了异常,我们正在处理它,所以我不想掩饰它.与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;
}