`
cjnetwork
  • 浏览: 177094 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

PreparedStatement、Statement、ResultSet等一定要手动关闭

阅读更多

     在使用java开发后台应用程序的时候,如果需要使用数据库,特别是试用第三方的数据库连接池的时候,使用完PreparedStatement等一定要手动关闭,最好是将关闭的代码写到finally中,保证一定能够完成关闭。
     
     原因有如下两点:

      1、第三方的数据库连接池,使用的时候,获取到Connection之后,使用完成,调用的关闭方法(close()) ,并没有将Connection关闭,只是放回到连接池中,如果调用的这个方法,而没有手动关闭PreparedStatement等,则这个PreparedStatement并没有关闭,这样会使得开发的程序内存急速增长,java的内存回收机制可能跟不上速度,最终造成Out of memory Error。
    
      2、如过在PreparedStatement等调用的时候,发生异常,则这个PreparedStatement是没有被关闭的,因此最好将PreparedStatement等的关闭写到finally代码中。


Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
 try {
    //do something
 } catch (SQLException e) {
    throw e;
 }finally{ 
    if(rs != null) try{rs.close();}catch (Exception e2) {}
    if(pst != null) try{pst.close();}catch (Exception e2) {}
    if(con!= null) try{con.close();}catch (Exception e2) {}
 }
1
7
分享到:
评论
2 楼 dandongsoft 2013-10-18  
异常里面也应该关闭吧
1 楼 mercyblitz 2011-05-22  
JDK 7就不用了,他们都实现了java.lang.AutoCloseable.

相关推荐

Global site tag (gtag.js) - Google Analytics