Search code examples
javatry-with-resources

Does try-with-resources on a statement close the connection?


In this code, would the connection be closed?

Connection con = DriverManager.getConnection(dbUrl, user, pass);
try (Statement st = con.createStatement()) {
    ResultSet rs = st.executeQuery(query);
}

Something in my code is unexpectedly closing the connection, I'd like to make sure it isn't this.


Solution

  • No, invoking close on Statement will not close Connection. This would prevent us from creating next statement on already opened connection which means we would have to create new Connection (which can be expensive operation) for each Statement.

    You can test it very easily. Just try to create another statement after previous one was closed.

    Connection con = DriverManager.getConnection(dbUrl,user,pass);
    try (Statement st = con.createStatement()) {
        ResultSet rs = st.executeQuery(sqlQuery1);
        simplePrint(rs);
    } catch (SQLException e) {
        e.printStackTrace();
    }//here `st` will be closed automatically by try-with-resources
    
    try (Statement st = con.createStatement()) {//lets try to create next statement
        ResultSet rs = st.executeQuery(sqlQuery2);
        simplePrint(rs);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    

    simplePrint method may look like this:

    public static void simplePrint(ResultSet rs) throws SQLException {
        ResultSetMetaData meta = rs.getMetaData();
        while (rs.next()) {
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                System.out.print(rs.getObject(i)+"\t");
            }
            System.out.println();
        }
    }