重用PreparedStatement

时间:2009-06-19 14:03:36

标签: java prepared-statement findbugs

我在我们的代码库上运行了findbugs,它指出还有两个语句仍然需要关闭。在我们运行的代码的这一部分中:

preparedStatement = connection.prepareStatement(query);

对于3个不同的查询,重用prepareStatement。在finally块中,我们关闭资源:

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);
   }

语句是否应在下一个connection.prepareStatement(query)之前关闭;或者这个发现者是否谨慎?

1 个答案:

答案 0 :(得分:8)

是的,在执行下一个connection.prepareStatement之前必须先关闭该语句。否则,您将丢失对未关闭的前一个(即泄漏语句)的引用。在每个语句使用周围尝试{} finally {},在finally中关闭它。

相关问题