數據庫連接是我們通常會創建出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){ }
}
}