在使用java开发后台应用程序的时候,如果需要使用数据库,特别是试用第三方的数据库连接池的时候,使用完PreparedStatement等一定要手动关闭,最好是将关闭的代码写到finally中,保证一定能够完成关闭。
原因有如下两点:
1、第三方的数据库连接池,使用的时候,获取到Connection之后,使用完成,调用的关闭方法(close()) ,并没有将Connection关闭,只是放回到连接池中,如果调用的这个方法,而没有手动关闭PreparedStatement等,则这个PreparedStatement并没有关闭,这样会使得开发的程序内存急速增长,java的内存回收机制可能跟不上速度,最终造成Out of memory Error。
2、如过在PreparedStatement等调用的时候,发生异常,则这个PreparedStatement是没有被关闭的,因此最好将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) {}
}
本文介绍了在Java开发中使用数据库连接池时的最佳实践,强调了手动关闭PreparedStatement的重要性,并解释了为何应在finally块中执行关闭操作,以避免内存泄漏和资源浪费。
1137

被折叠的 条评论
为什么被折叠?



