資料庫連接是我們通常會建立出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){ } }}