... will the connection end automatically after the method returns?
No, it will not. In the end, it may or may not end, but it will be a long time before it happens, if ever. A connection class finalizer probably closes the connection if it opens, but there are many situations where finalizers never start. Must be explicitly called con.close().
( , ):
public static void C()
throws SQLException
{
Connection con = DriverManager.getConnection();
try {
....
con.close();
con = null;
}
finally {
if (con != null) {
try {
con.close();
}
catch (Exception e) {
}
}
}
}
, , finally, , , - , . , , , finally, , , , con.close().
:
public static void C()
throws SQLException
{
Connection con = DriverManager.getConnection();
try {
....
con = JDBCHelper.close(con);
}
finally {
con = JDBCHelper.quietClose(con);
}
}
... 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;
}