2011-07-15 40 views
9

使用PreparedStatements和ResultSets時,每次使用它們時都會創建一個「新數據庫實例」? 或者換句話說,如果我使用PreparedStatement和ResultSet,我應該在每次使用後還是一次完成後關閉它們?Closing PreparedStatements

例子:

while (...){ 
     p = connection.prepareStatement(...); 
     r = p.executeQuery(); 
     while (r.next()) { 
     .... 
     } 
} 
// We close at the end. Or there are any other p and r still opened...? 
p.close(); 
r.close(); 

OR

while (...){ 
     p = connection.prepareStatement(...); 
     r = p.executeQuery(); 
     while (r.next()) { 
     .... 
     } 
     p.close(); 
     r.close(); 
} 

注:當然,我會用盡量接近正常,這只是一個例子。

+0

您可以在finally塊中關閉它們,這樣即使存在任何運行時間異常,也可以確保它關閉 – chedine

回答

5

你應該關閉你打開的每一個。當你創建一個準備好的語句或結果集時,數據庫會爲這些資源分配資源,關閉這些資源會告訴數據庫釋放這些資源(可能數據庫會在超時後最終重新分配這些資源,但通過close調用可以讓數據庫知道它可以繼續並清理)。你的第二個例子比較好,除了在準備好的語句之前關閉結果集。

與try塊

所以包括它看起來像:

while (...){ 
     PreparedStatement p = connection.prepareStatement(...); 
     try { 
      ResultSet r = p.executeQuery(); 
      try { 
      while (r.next()) { 
       .... 
      } 
      } finally { 
      try { 
       r.close(); 
      } catch (SQLException e) { 
      // log this or something -- prevent these from masking original exception 
      } 
      } 
     } 
     finally { 
      try { 
      p.close(); 
      } catch (SQLException e) { 
      // log this or something -- prevent these from masking original exception 
      } 
     } 
} 

捕獲異常從接近是醜陋的,但如果你有準備的語句的執行過程中拋出一個異常,或者結果進行遍歷期間設置,你要確保你看到它,而不是關閉準備好的語句或結果集時引發的異常(這是由於某些網絡故障導致無法執行任何操作)。

另外請注意,使用try-with-resources將起作用,除非如果你有一個數據庫操作成功的情況,但是調用close結果導致異常,那麼異常將被拋出。

我建議人們使用spring-jdbc庫(它處理關閉所有內容),而不是用手動啓動iffy或verbose jdbc。

+0

這裏的任何幫助? :) http://stackoverflow.com/questions/35849664/sonar-close-this-preparedstatement –

5

第一種方式更好。

但是,如果每次使用的SQL都相同,則應該知道可以重新使用預準備語句(因此名稱爲「準備好」)。例如:

//Note: try/catch/finally blocks removed for brevity 
p = connection.prepareStatement(...); 
while (...){ 
    r = p.executeQuery(); 
    while (r.next()) { 
     .... 
    } 
    r.close(); 
} 
p.close(); 
+1

+1重新使用準備好的語句 –

+0

任何幫助嗎? :) http://stackoverflow.com/questions/35849664/sonar-close-this-preparedstatement –

1

即使你不想使用Spring,或Apache DbUtils,或類似的,認識到有樣板很多在這裏,你要不斷分解出您的查詢程序,讓你必須儘可能少地重複。