Vincent.Chan‘s Blog

          常用鏈接

          統(tǒng)計(jì)

          積分與排名

          網(wǎng)站

          最新評(píng)論

          關(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

          主站蜘蛛池模板: 犍为县| 广丰县| 曲水县| 德清县| 舟山市| 当涂县| 理塘县| 奉化市| 宝兴县| 阿拉尔市| 宜阳县| 融水| 库伦旗| 保德县| 金寨县| 南岸区| 新兴县| 治县。| 临沭县| 揭东县| 平度市| 海安县| 搜索| 宜川县| 谷城县| 抚远县| 青海省| 邹城市| 土默特右旗| 珲春市| 安宁市| 山东省| 镇巴县| 崇仁县| 景洪市| 新竹市| 浦东新区| 炎陵县| 高陵县| 新河县| 嫩江县|