*
The moose likes JDBC and the fly likes Why do we need to close the ResultSet? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Why do we need to close the ResultSet?" Watch "Why do we need to close the ResultSet?" New topic
Author

Why do we need to close the ResultSet?

Er. Sandeep
Greenhorn

Joined: Aug 28, 2005
Posts: 1
why do we need to close the ResultSet or Statement objects explicitly every time we use it?Can any body tell me what will happen if we dont close these
objects explicitly?
Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
Failure to close these objects makes it more likely that you will exceed the number of available database cursors. For instance, Oracle reports an ORA-01000 error. When this error is propagated to an application server such as WebLogic Server, SQLException is thrown with a message like this:


Also, failure to close a Statement object can cause a database lock to be retained unnecessarily.

Even if objects are closed just after usage, you should ensure closure in the finally block. Note that each closure is done in a separate try/catch block.


SCJP 1.4, SCWCD 1.3, SCBCD 1.3
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Roger hinted but didn't quite state that ResultSEts and some other things in JDBC are database resources, not Java resources. Java is pretty good at memory management, although it is still possible to create memory (or 'resource') leakage it isn't quite as easy as it once was.

Things change when you mix Java with external applications. If these applications manage a finite number of resources, Java can try to get it right for you but may not be perfect. I believe you can have similar problems in AWT if you don't close some of the resources.

Personally I prefer the defensive technique: Always try to make sure you release resources when required, because if it ever becomes an issue it will take you two weeks or more to diagnose and fix the problem
Sirish Kumar Gongal Reddy
Ranch Hand

Joined: Oct 25, 2004
Posts: 109
Hi,
what David O'Meara said is exaclty suitable.if you won't close your resultset object or statement,connection objects what exaclty happnes is before serving your requst it(ResultSet) occupies some memory on the heap right?if you won't close the object explicitly it (Object) won't release the resources which it consumes until the garbage collector will come into the picture.
what ever resources you are consumed from heap if you release it explicity it leads efficient memory management.this is one of the reason.
It is strictly applied for Connectionpooling in JDBC.
Thanks,
G Sirish Reddy.,
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why do we need to close the ResultSet?