3

Consider the following code

ResultSet rs = null;
Statement st = null;
try {
  //do somehting
 } catch (Exception e){
  //do something
 } finally {
     if(st != null){
       try {
       st.close();
       } catch (SQLException e) {
            log.error("Exception while closing statement: " + e);
       }
    }
 }

The question is that when we close the statement, will it close the result set as well or do we need to explicitly close the result set like this

if(rs != null){
   try {
   rs.close();
   } catch (SQLException e) {
        log.error("Exception while closing result set: " + e);
   }
}

I thought that closing the statement will automatically close the result set, but FindBugs throws the following warning if I don't explicitly close the result set

This method may fail to clean up java.sql.ResultSet

comatose
  • 1,952
  • 7
  • 26
  • 42

3 Answers3

7

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

This and this shows that Oracle may have problems and you might have to explicitly close the ResultSet. But again, as per the Javadocs, this shouldn't be an issue. Hence, the warning,maybe.

Community
  • 1
  • 1
Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
  • any ideas then why FindBugs reports a warning for this one ? – comatose May 15 '12 at 14:02
  • 1
    It might be legacy. IIRC, closing ResultSets when the Statement is closed wasn't always in the JDBC spec (a looong time ago, like 1.2ish). There are probably drivers out there that don't do it properly. – Sean Reilly May 15 '12 at 14:06
3

You can't count on the ResultSet being closed automatically, it depends on the driver implementation and how compliant it is. The best policy is to close the ResultSet explicitly.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
1

When you close the statement or connection, all it's children should be closed too by default.

OmniOwl
  • 5,477
  • 17
  • 67
  • 116