LeedMx
LeedMx

Reputation: 434

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.

Upvotes: 0

Views: 58

Answers (1)

Mark Rotteveel
Mark Rotteveel

Reputation: 109012

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.

Upvotes: 3

Related Questions