Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ResultSet not closed when connection closed?

I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode):

Connection conn = dataSource.getConnection();  try{     PreparedStatement stmt = conn.prepareStatement();     //initialize the statement     stmt.execute();     ResultSet rs =  stmt.getResultSet();     //get data }finally{     conn.close(); } 

The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally:

finally{     try{         rs.close()     }catch(SqlException se){         //log it     }     try{         stmt.close();     }catch(SqlException se){         //log it     }     conn.close(); } 

But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements.

Did you have troubles with ResultSets and Statements not being closed when the Connection is closed?

I found only this and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.

like image 390
jb. Avatar asked Sep 19 '08 17:09

jb.


People also ask

Does closing connection close ResultSet?

Yes it does, Connection. close API says "Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released".

Does ResultSet need to be closed?

You should explicitly close Statements , ResultSets , and Connections when you no longer need them, unless you declare them in a try -with-resources statement (available in JDK 7 and after). Connections to Derby are resources external to an application, and the garbage collector will not close them automatically.

How do I know if a ResultSet is closed?

The ResultSet object contains a cursor/pointer which points to the current row. Initially this cursor is positioned before first row (default position). The isClosed() method of the ResultSet interface is used to determine whether the current ResultSet object is closed.


2 Answers

One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the connection.close() would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it is explicitly closed.

like image 108
Aaron Avatar answered Sep 21 '22 01:09

Aaron


I've had problems with unclosed ResultSets in Oracle, even though the connection was closed. The error I got was

"ORA-01000: maximum open cursors exceeded" 

So: Always close your ResultSet!

like image 38
neu242 Avatar answered Sep 18 '22 01:09

neu242