關于ResultSet的關閉問題
在Connection上調用close方法會關閉Statement和ResultSet嗎?
級聯的關閉這聽起來好像很有道理,而且在很多地方這樣做也是正確的,通常這樣寫
Connection con = getConnection();//getConnection is your method
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
……
///rs.close();
///ps.close();
con.close(); // NO!
這
樣做的問題在于Connection是個接口,它的close實現可能是多種多樣的。在普通情況下,你用
DriverManager.getConnection()得到一個Connection實例,調用它的close方法會關閉Statement和
ResultSet。但是在很多時候,你需要使用數據庫連接池,在連接池中的得到的Connection上調用close方法的時候,Connection可能并沒有被釋放,而是回到了連接池中。它以后可能被其它代碼取出來用。如果沒有釋放Statement和ResultSet,那么在Connection上沒有關閉的Statement和ResultSet可能會越來越多,那么……
相反,我看到過這樣的說法,有人把Connection關閉了,卻繼續使用ResultSet,認為這樣是可以的,引發了激烈的討論,到底是怎么回事就不用我多說了吧。
所以我們必須很小心的釋放數據庫資源,下面的代碼片斷展示了這個過程
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();//getConnection is your method
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
///...........
}
catch (SQLException ex) {
///錯誤處理
}
finally{
try {
if(ps!=null)
ps.close();
}
catch (SQLException ex) {
///錯誤處理
}
try{
if(con!=null)
con.close();
}
catch (SQLException ex) {
///錯誤處理
}
}
很麻煩是不是?但為了寫出健壯的程序,這些處理是必須的。
posted on 2006-03-15 23:15 Vincent.Chen 閱讀(4368) 評論(0) 編輯 收藏 所屬分類: Java