读书人

PreparedStatement、Statement、Resul

发布时间: 2012-08-24 10:00:21 作者: rapoo

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 楼 mercyblitz 2011-05-22 JDK 7就不用了,他们都实现了java.lang.AutoCloseable.

读书人网 >软件架构设计

热点推荐