当前位置:   article > 正文

[JDBC]正确关闭connection_jdbc connection close

jdbc connection close

Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
   conn = DriverManager.getConnection(“jdbc:mysql://127.0.0.1/test”,“root”,“123456”);
   stmt = conn.prepareStatement(“select 1 from table”);
   rs = stmt.executeQuery();
   while(rs.next()){
     System.out.println(“OK”);
   }
} catch (SQLException e) {
  e.printStackTrace();
}finally{
   try {
     if(rs != null){
       rs.close();
     }
     if(stmt != null){
       stmt.close();
     }
     if(conn != null){
       conn.close();
     }
   } catch (SQLException e) {
         e.printStackTrace();
     }
  }
上面是一段很常见的jdbc代码.通常,我们都是在finally里释放资源,经常可以看到有人或者为了美观,或者为了省事,将rs.close(),stmt.close(),conn.close()放到同一个try,catch块中.事实上,这样子关闭是不够严谨是.如果rs.close()或者stmt.close()执行的时候抛出了异常,那么就不会执行conn.close(),也就没法正确关闭connection了.
为了保证connection可以正常关闭,我们稍微调整一下代码.如下:

          try{
                if(rs!= null){
                    rs.close();
                }
             }catch(SQLException e){
                   //handle the exception
             }finally{
                 try{
                    if(stmt!= null){
                        stmt.close();
                    }
                 }catch(SQLException e){
                      //handle the exception
                 }finally{                               
		              try{
		                    if(conn!= null){
		                        conn.close();
		                    }
		                }catch(SQLException e){
		                       //handle the exception
		                  }
                 }
             }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

这样的写法虽然正确,但还可以将代码再简洁些,就是在方法上声明throws SQLException,方法体中这样关闭。

            try {
                 if(rs != null){
                    rs.close();//(1)
                }
            } finally{
                try{
                    if(stmt != null){
                        stmt.close();//(2)
                    }
                }finally{
                    if(conn != null){
                        conn.close();//(3)
                    }
                }
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/748954
推荐阅读
相关标签
  

闽ICP备14008679号