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