Vincent.Chan‘s Blog

          常用鏈接

          統(tǒng)計

          積分與排名

          網(wǎng)站

          最新評論

          關(guān)于ResultSet的關(guān)閉問題

          在Connection上調(diào)用close方法會關(guān)閉Statement和ResultSet嗎?

          級聯(lián)的關(guān)閉這聽起來好像很有道理,而且在很多地方這樣做也是正確的,通常這樣寫
          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實現(xiàn)可能是多種多樣的。在普通情況下,你用 DriverManager.getConnection()得到一個Connection實例,調(diào)用它的close方法會關(guān)閉Statement和 ResultSet。但是在很多時候,你需要使用數(shù)據(jù)庫連接池,在連接池中的得到的Connection上調(diào)用close方法的時候,Connection可能并沒有被釋放,而是回到了連接池中。它以后可能被其它代碼取出來用。如果沒有釋放Statement和ResultSet,那么在Connection上沒有關(guān)閉的Statement和ResultSet可能會越來越多,那么……
          相反,我看到過這樣的說法,有人把Connection關(guān)閉了,卻繼續(xù)使用ResultSet,認(rèn)為這樣是可以的,引發(fā)了激烈的討論,到底是怎么回事就不用我多說了吧。

          所以我們必須很小心的釋放數(shù)據(jù)庫資源,下面的代碼片斷展示了這個過程

          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 閱讀(4380) 評論(0)  編輯  收藏 所屬分類: Java

          主站蜘蛛池模板: 通许县| 嘉义市| 昭苏县| 饶河县| 石阡县| 连云港市| 宜良县| 昭通市| 玛沁县| 信阳市| 花垣县| 弥渡县| 堆龙德庆县| 汤阴县| 自治县| 兴海县| 贵州省| 内江市| 柘荣县| 休宁县| 门头沟区| 宕昌县| 钦州市| 建平县| 景泰县| 西畴县| 内黄县| 延庆县| 奉节县| 葵青区| 陆丰市| 凤山市| 禹州市| 泸西县| 运城市| 鲁山县| 海南省| 宁南县| 峨眉山市| 顺平县| 宕昌县|