2009-06-19 68 views
3

我跑了我們的代碼庫FindBugs的,它指出,還有兩個語句仍然需要被關閉。在這段代碼中,我們運行:重用一個PreparedStatement

preparedStatement = connection.prepareStatement(query); 

3個不同的查詢,重新使用preparedStatement。 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(查詢)之前被關閉;或者這個findbugs是謹慎的?

+2

無論你需要的參考是無關緊要的。當您調用connection.prepareStatement(query)時,您正在該連接中創建一個preparedStatement。那些人將坐在那裏直到連接關閉。當你最終打開時,你只會關閉該變量指向的預備語句。在連接關閉之前,留下3箇中的2個。在生產中,你會繼續泄漏連接,最終耗盡,如果你不removeAbandoned(Tomcat)的等。 – Zach 2009-06-19 14:23:35

+0

感謝您的解釋!添加了變化:) – 2009-06-19 14:28:24

回答

8

是的,你進行下一步之前,各種Connection.prepareStatement聲明必須關閉。否則,你失去了對未關閉的前一個(也就是泄漏語句)的引用。在每個語句use周圍包裝一個try {},最後在finally中關閉它。