数据库连接是我们通常会创建出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){ } } }