Skip to Main Content

Java Database Connectivity (JDBC)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Best practices for closing ResultSet and CallableStatement within loop.

843854Feb 4 2005 — edited Feb 5 2005
Hi,

I have the code below and it's run fine. I would like to know whether it's the correct way to close the ResultSet and Statement within a loop.

Let's say I have a loop that calls the same stored proc to query record. It goes thru the loop 5 times and each time it passes in an index value, ie: 1, 2, 3, 4, 5. Right now, I close the ResultSet and CallableStatement at the end of my for loop (see bold statement below). Is that the right place for closing the database resources to provide better performance?
ResultSet rs = null;
CallableStatement cs = null;
Connection conn = null;
			
try {
   conn = getConnection();
   String query = "{?= call my_stored_proc(?)}";
   cs = conn.prepareCall(query);				
   cs.registerOutParameter(1, Types.INTEGER);				
   HashMap report = new HashMap();
   for (int i = 1; i <= 5; i++) {
      cs.setInt(2, i);
      rs = cs.executeQuery();
      if (rs != null && rs.first()) {
         // get the data from resultset here...
      }
      rs.close();
      cs.close();		
   } // end for loop
} catch (SQLException e) {
   // error !!!
} finally {
   // release object's database and JDBC resources
   rs.close();
   cs.close();
   conn.close();
}
Thanks,
Tuan
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 5 2005
Added on Feb 4 2005
8 comments
2,083 views