Java資料庫操作時一點常見的錯誤

來源:互聯網
上載者:User

         資料庫連接是我們通常會建立出Connection、Statement、ResultSet的對象,新手可能會如下使用:

Connection connection=DriverManager.getConnection(“資料庫 的url”);Statement statement =connection.createStatement();//接著是一些操作資料庫的JDBC代碼ResultSet resultSet = …………resultSet.close();statement.close();connection.close();

以上方法是錯誤的。因為如果與資料庫建立了串連即getConnection()和close()之間的拋出了異常(SQLException),這時,close()就會完全被忽略了。

釋放資料庫的串連和 JDBC 資源的正確方式是把close()放到try-catch-finally異常處理的finally塊中。修改如下:

Connection connection = null;Statement statement = null;ResultSet resultSet = null;try{  connection = DriverManager.getConnection("資料庫 的url");  statement = connection.createStatement();   //接著是一些操作資料庫的JDBC代碼  resultSet = ……   ……}catch(SQLException e){   ……}finally{  if(resultSet != null){    resultSet.close();   }  if(statement != null){    statement.close();   }  if(statement != null){    connection.close();   }} 

      但是close也可能會拋出SQLException異常,當程式運行到resultSet.close()時拋出了SQLException異常,那麼接下的語句也會被忽略。所以最保險的方式是每個close()使用try-catch,如下所示:

Connection connection = null;Statement statement = null;ResultSet resultSet = null;try{   connection=DriverManager.getConnection(“資料庫 的url”);   statement= connection.createStatement();   //接著是一些操作資料庫的JDBC代碼resultSet = …………   resultSet= ……   }catch(SQLExceptione){      ……   }finally{      try{        resultSet.close();        }catch(SQLExceptione){ }      try{        statement.close();      }catch(SQLExceptione){ }      try{        connection.close();      }catch(SQLExceptione){ }   }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.