This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes JDBC and Relational Databases and the fly likes Question on closing ResultSets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Question on closing ResultSets" Watch "Question on closing ResultSets" New topic

Question on closing ResultSets

Chris Cano

Joined: Mar 14, 2011
Posts: 2
According to the Javadocs for ResultSet,
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

Why, then, do I keep seeing examples like this?

Isn't closing the ResultSet superfluous, since the Statement is being closed right afterwards?
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 32815

Chris Cano wrote:Isn't closing the ResultSet superfluous, since the Statement is being closed right afterwards?

Yes. However some drivers don't implement the spec properly so people got in the habit of closing both. I do the same. No harm in it.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Chris Cano

Joined: Mar 14, 2011
Posts: 2
Alright, thanks.

How about the part about when the Statement is re-executed? If I have a PreparedStatement executing a query in a loop (or just any reuse of a PreparedStatement), do I need to close the ResultSet from each execution of the PreparedStatement?
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3749

You should close the result set if you are going to reuse a statement. While not closing it won't kill your application, if the life of the statement is significantly long, you could end up with a lot of unclosed result sets. Keep in mind, garbage collection will not close an object. As Jeanne pointed out, though, you should always close both when you're done with them since you can't predict what a driver is going to do and because its a good practice. Not closing JDBC objects properly can lead to a lot of bugs as an application scales to more and more users.

I wrote an article about closing JDBC objects a few years back you might find of use.

[OCA 8 Book] [Blog]
I agree. Here's the link:
subject: Question on closing ResultSets
jQuery in Action, 3rd edition