295

It is said to be a good habit to close all JDBC resources after usage. But if I have the following code, is it necessary to close the Resultset and the Statement?

Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
    conn = // Retrieve connection
    stmt = conn.prepareStatement(// Some SQL);
    rs = stmt.executeQuery();
} catch(Exception e) {
    // Error Handling
} finally {
    try { if (rs != null) rs.close(); } catch (Exception e) {};
    try { if (stmt != null) stmt.close(); } catch (Exception e) {};
    try { if (conn != null) conn.close(); } catch (Exception e) {};
}

The question is if the closing of the connection does the job or if it leaves some resources in use.

1

12 Answers 12

228

What you have done is perfect and very good practice.

The reason I say its good practice... For example, if for some reason you are using a "primitive" type of database pooling and you call connection.close(), the connection will be returned to the pool and the ResultSet/Statement will never be closed and then you will run into many different new problems!

So you can't always count on connection.close() to clean up.

13
  • 5
    ... and the most evident reason to close everything explicitly.
    – Zeemee
    Dec 23, 2010 at 9:25
  • 2
    I agree that it is good practice to close result sets and statements. However, the result sets and statements are garbage collected - they don't stay open forever and you don't "run into many different new problems".
    – stepanian
    Sep 7, 2011 at 9:16
  • 3
    @Ralph Stevens - You cannot count on that. I have had a situation where the MSSQL JDBC driver leaked memory because the ResultSet's were not closed, even after being garbage collected.
    – Paul
    Sep 8, 2011 at 5:52
  • 7
    @Paul - Interesting. That sounds to me like a shortcoming of the JDBC driver.
    – stepanian
    Sep 9, 2011 at 20:31
  • 2
    @tleb - that would work as expected. although in theory, exceptions are "expensive" so there would be a very small performance knock (which you have already identified)
    – Paul
    Oct 16, 2016 at 18:08
138

Java 1.7 makes our lives much easier thanks to the try-with-resources statement.

try (Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement()) {
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do stuff with the result set.
    }
    try (ResultSet resultSet = statement.executeQuery("some query")) {
        // Do more stuff with the second result set.
    }
}

This syntax is quite brief and elegant. And connection will indeed be closed even when the statement couldn't be created.

10
  • 65
    You don't need to nest like this, you can do it all in one try-with-resources, just treat the resource declarations as separate statements (separated by ;) Aug 19, 2013 at 7:59
  • 3
    Mark Rotteveel: you can use a single try for all three Connection, Statement and ResultSet, but if you want to perform several queries, you must close the previous ResultSet before starting a new query. At least that is the way how the DBMS I was using worked. Oct 17, 2015 at 13:39
  • why won't you do something like this ? try(open connection){ try(multiple statements & resultsets){ especially when next queries results can compute with previous ones. Nov 26, 2015 at 11:07
  • Daniel: When I used that pattern, the underlying JDBC backend did not support keeping a ResultSet open and open a second one. Nov 27, 2015 at 11:27
  • 1
    @gstackoverflow That is an entirely different problem, I was commenting on the fact that this answer originally had three levels of nested try-with-resource, while the first two levels could be combined into a single try-with-resources by specifying both the connection and the statement in the same resource definition. In other words, as the answer is now. Apr 10, 2021 at 6:05
78

From the javadocs:

When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

However, the javadocs are not very clear on whether the Statement and ResultSet are closed when you close the underlying Connection. They simply state that closing a Connection:

Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.

In my opinion, always explicitly close ResultSets, Statements and Connections when you are finished with them as the implementation of close could vary between database drivers.

You can save yourself a lot of boiler-plate code by using methods such as closeQuietly in DBUtils from Apache.

2
46

I'm now using Oracle with Java. Here my point of view :

You should close ResultSet and Statement explicitly because Oracle has problems previously with keeping the cursors open even after closing the connection. If you don't close the ResultSet (cursor) it will throw an error like Maximum open cursors exceeded.

I think you may encounter with the same problem with other databases you use.

Here is tutorial Close ResultSet when finished:

Close ResultSet when finished

Close ResultSet object as soon as you finish working with ResultSet object even though Statement object closes the ResultSet object implicitly when it closes, closing ResultSet explicitly gives chance to garbage collector to recollect memory as early as possible because ResultSet object may occupy lot of memory depending on query.

ResultSet.close();

8
  • Thanks hilal, these are good reasons to close it as early as possible. However, does it matter if ResultSet and Statement are closed direcly before the Connection (this means in some cases: not as early as possible)?
    – Zeemee
    Dec 22, 2010 at 9:02
  • If you close connection, it will close all the resultset ans statement also but you should close resultset before the connection
    – user467871
    Dec 22, 2010 at 9:07
  • And why should i close the resultset before the connection? You mean because of the oracle driver problems?
    – Zeemee
    Dec 22, 2010 at 9:12
  • 1
    here is more general clarification :) stackoverflow.com/questions/103938/…
    – user467871
    Dec 22, 2010 at 11:02
  • In theory, if you close the statement you don't have to close the resultsets, but it's probably good practice.
    – rogerdpack
    Nov 22, 2013 at 21:45
9

If you want more compact code, I suggest using Apache Commons DbUtils. In this case:

Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
    conn = // Retrieve connection
    stmt = conn.prepareStatement(// Some SQL);
    rs = stmt.executeQuery();
} catch(Exception e) {
    // Error Handling
} finally {
    DbUtils.closeQuietly(rs);
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(conn);
}
1
  • 3
    what will happen if i use this code instead of rs.close(), stmt.close(), conn.close() Mar 25, 2019 at 13:41
6

No you are not required to close anything BUT the connection. Per JDBC specs closing any higher object will automatically close lower objects. Closing Connection will close any Statements that connection has created. Closing any Statement will close all ResultSets that were created by that Statement. Doesn't matter if Connection is poolable or not. Even poolable connection has to clean before returning to the pool.

Of course you might have long nested loops on the Connection creating lots of statements, then closing them is appropriate. I almost never close ResultSet though, seems excessive when closing Statement or Connection WILL close them.

0
3

Doesn't matter if Connection is poolable or not. Even poolable connection has to clean before returning to the pool.

"Clean" usually means closing resultsets & rolling back any pending transactions but not closing the connection. Otherwise pooling looses its sense.

2

The correct and safe method for close the resources associated with JDBC this (taken from How to Close JDBC Resources Properly – Every Time):

Connection connection = dataSource.getConnection();
try {
    Statement statement = connection.createStatement();

    try {
        ResultSet resultSet = statement.executeQuery("some query");

        try {
            // Do stuff with the result set.
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
} finally {
    connection.close();
}
0
1

I created the following Method to create reusable One Liner:

public void oneMethodToCloseThemAll(ResultSet resultSet, Statement statement, Connection connection) {
    if (resultSet != null) {
        try {
            if (!resultSet.isClosed()) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (statement != null) {
        try {
            if (!statement.isClosed()) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if (connection != null) {
        try {
            if (!connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

I use this Code in a parent Class thats inherited to all my classes that send DB Queries. I can use the Oneliner on all Queries, even if i do not have a resultSet.The Method takes care of closing the ResultSet, Statement, Connection in the correct order. This is what my finally block looks like.

finally {
    oneMethodToCloseThemAll(resultSet, preStatement, sqlConnection);
}
-1

With Java 6 form I think is better to check it is closed or not before close (for example if some connection pooler evict the connection in other thread) - for example some network problem - the statement and resultset state can be come closed. (it is not often happens, but I had this problem with Oracle and DBCP). My pattern is for that (in older Java syntax) is:

try {
    //...   
    return resp;
} finally {
    if (rs != null && !rs.isClosed()) {
        try {
            rs.close();
        } catch (Exception e2) { 
            log.warn("Cannot close resultset: " + e2.getMessage());
        }
    }
    if (stmt != null && !stmt.isClosed()) {
        try {
            stmt.close();
        } catch (Exception e2) {
            log.warn("Cannot close statement " + e2.getMessage()); 
        }
    }
    if (con != null && !conn.isClosed()) {
        try {
            con.close();
        } catch (Exception e2) {
            log.warn("Cannot close connection: " + e2.getMessage());
        }
    }
}

In theory it is not 100% perfect because between the the checking the close state and the close itself there is a little room for the change for state. In the worst case you will get a warning in long. - but it is lesser than the possibility of state change in long run queries. We are using this pattern in production with an "avarage" load (150 simultanous user) and we had no problem with it - so never see that warning message.

1
  • You don't need the isClosed() tests, because closing any of these that is already closed is a no-op. Which eliminates the timing window problem. Which would also be eliminated by making the Connection, Statement, and ResultSet local variables.
    – user207421
    Aug 10, 2017 at 7:11
-2

Some convenience functions:

public static void silentCloseResultSets(Statement st) {
    try {
        while (!(!st.getMoreResults() && (st.getUpdateCount() == -1))) {}
    } catch (SQLException ignore) {}
}
public static void silentCloseResultSets(Statement ...statements) {
    for (Statement st: statements) silentCloseResultSets(st);
}
3
  • There is nothing here that closes anything. Just a pointless loop that wastefully reads the entire response, even though it clearly isn't wanted any more.
    – user207421
    Jun 11, 2020 at 10:02
  • st.getMoreResults() in the loop does all the work regardless of how many (if any) results were fetched and type (INSERT / UPSERT) of the result. It's the most universal solution
    – Mad Calm
    Aug 1, 2020 at 18:06
  • It's a universal solution for iterating all of the returned data without really using any of it, and further #getMoreResults (without flags) will only auto-close ResultSet, not the Statement object in question. Your method's wording makes it seem like you're answering the wrong question.
    – Rogue
    Feb 6 at 14:29
-3

As far as I remember, in the current JDBC, Resultsets and statements implement the AutoCloseable interface. That means they are closed automatically upon being destroyed or going out of scope.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.