JDBC: Connection break if I lose the link to the Connection object?

If I have the following method -

public static void C()  {
    Connection con = DriverManager.getConnection();

    .... // code

    return;
}

and I don’t call con.close(), will the connection end automatically after the method returns?

+3
source share
3 answers

... 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 {
        .... // 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;
}
+3

. Connection , , , . , .

, , , Connection. finally ( ):

Connection conn = DriverManager.getConnection(...);
try {
    // ... code that uses the connection
}
finally {
    // Close the connection
    conn.close();
}
+1

Source: https://habr.com/ru/post/1748717/


All Articles