简体   繁体   中英

Will this try with resources close my Connection?

Will this Connection be closed after the try with resources?

public static String readString(String connection, String sql) throws SQLException {
    try (ResultSet rs = DriverManager.getConnection(connection).createStatement(sql).executeQuery()) {
        if (rs.next()) {
            return rs.getString(1);
        }
    }
    return "";
}

I'm sure that the ResultSet will, not sure about the connection.

Even more intriguing, what if I generate the connection in a different method?:

public static String readString(String connection, String sql) throws SQLException {
    try (ResultSet rs = myMethod(connection).createStatement(sql).executeQuery()) {
        if (rs.next()) {
            return rs.getString(1);
        }
    }
    return "";
}

Connection myMethod(String connection){
    return DriverManager.getConnection(connection);
}

This puzzles me because I'am having some memory leaking, but I'm not sure if this could be the culprit.

No, the connection and the statement will not be closed in your code (though they might be reclaimed at a later point by the garbage collector). A try-with-resources will only close the objects that are assigned to the variables in the resources-clause. So intermediate objects created inside the clause that are not assigned to a variable will not be closed by the try-with-resources.

The only thing that ensures everything gets closed is to use:

try (Connection conn = DriverManager.getConnection(connection);
     Statement stmt = conn.createStatement();
     ResultSet rs = stmt.executeQuery(sql)) {
    // ...
}

And yes, technically, statements will get closed when the connection gets closed. That is not a good reason to skip declaring a resource correctly though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM