This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JDBC and the fly likes Closing ResultSet and Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Closing ResultSet and Statement" Watch "Closing ResultSet and Statement" New topic
Author

Closing ResultSet and Statement

Mila Shanoy
Greenhorn

Joined: Aug 21, 2003
Posts: 5
I am cleaning up/debugging the following code:
stmt = conn.createStatement();
stmt.execute(some_select_query1);
rs = stmt.getResultSet();
// ..... some code that uses rs ....
stmt.execute(some_select_query2);
rs = stmt.getResultSet();
// ..... some code that uses rs ....

My question is: does the code leave hanging resultset objects? Does it need rs.close() before each 'rs = stmt.getResultSet();'
What is your opinion/experience on that?
Thank you.
Sean Sullivan
Ranch Hand

Joined: Sep 09, 2001
Posts: 427
I recommend closing each ResultSet by calling close()
I usually close the ResultSet and the Statment in a finally block.
James Redpath
Greenhorn

Joined: Aug 02, 2003
Posts: 13
I have ran into this myself. Here's the story from Oracle. The drivers do not have finializer methods; cleanup routines are performed by the close() method of the ResultSet and Statement classes. If you do not explicitly close your ResultSet and Statement objects (I stress AND here), serious memory leaks could occur. Plus you could run out of cursors in the database. (this has happen to me). Closing the result set or statment releases the corrsponding cusor in the database. So close for each rs/stmt, your connection will still stay open! Then create rs/stmt again
s = new String("Select * from user_tables");
Try{ stmt=conn.createStatement();
rs = stmt.executeQuery(s);
rs.close();
stmt.close();
}catch (SQLException sqle) {}
.... some building of new string
Try{ stmt=conn.createStatement();
rs = stmt.executeQuery(s);
rs.close();
stmt.close();
}catch (SQLException sqle) {}
Mila Shanoy
Greenhorn

Joined: Aug 21, 2003
Posts: 5
Thank you. You confirmed my suspicions.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Closing ResultSet and Statement
 
Similar Threads
executeQuery( ) method
Data Access Object Design pattern . How to use it..
Working with Temporary Table
Oracle -- Closing Statements
Once executed and accessing multiple times?