Java数据库操作时一点常见的错误

本文介绍了在Java中正确处理数据库连接及JDBC资源的方法。为了避免资源泄露,文章建议使用try-catch-finally结构来确保所有打开的资源都能被正确关闭,并推荐在每个close()调用上使用try-catch以捕获并处理可能发生的SQLException。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值