views:

356

answers:

1

I ran findbugs on our code base and it pointed out there are two more Statements that still need to be closed. In this section of the code we run:

preparedStatement = connection.prepareStatement(query);

for 3 different queries, reusing preparedStatement. In the finally block we do close the resource:

finally{
   try{
      if (resultSet != null) 
         resultSet.close();
   } catch (Exception e) {
      exceptionHandler.ignore(e);
   }
   try {
      if (preparedStatement != null) 
         preparedStatement.close();
   } catch(Exception e) {
      exceptionHandler.ignore(e);
   }

Should the statement be closed before the next connection.prepareStatement(query); or is this findbugs being cautious?

+7  A: 

Yes, the statement must be closed before you perform the next connection.prepareStatement. Otherwise, you're losing your reference to the un-closed previous one (aka leaking statements). Wrap a try {} finally {} around each statement use, closing it in the finally.

MarquisDeMizzle
Just like to also point out that while closing the connection should clean up the leaked statements, better off to close each one individually. If this code got repeated multiple times in an open connection you'd find yourself running out of resources ( 2 statements at a time =] )
MarquisDeMizzle