在使用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) {}
}
分享到:
相关推荐
java中PreparedStatement和Statement的区别
Statement和PreparedStatement之间的区别
jdbc中preparedStatement比Statement的好处
这个问题其实也很简单,因为PreparedStatement接口必须通过Connection接口来获取实例,而ResultSet接口又必须从Statement或者PreparedStatement接口来获取实例,有了这样的级联关系,问题也就迎刃而解了。...
Java面试题34.jdbc中preparedStatement比Statement的好处.mp4
主要介绍了Java使用PreparedStatement接口及ResultSet结果集的方法,结合实例形式分析了PreparedStatement接口及ResultSet结果集的相关使用方法与操作注意事项,需要的朋友可以参考下
主要介绍了java中PreparedStatement和Statement详细讲解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
NULL 博文链接:https://stevenjohn.iteye.com/blog/968877
NULL 博文链接:https://chaoyi.iteye.com/blog/2088080
jdbc2.0版 PreparedStatement接口的用法
NULL 博文链接:https://huiminchen.iteye.com/blog/1097332
什么时候用statement,什么时候用preparedstatement
Statement st=con.createStatement(); //获取PreparedStatement对象 ResultSet rs=st.executeQuery(sqlStr); //执行查询 //在网页中输出查询结果 PrintWriter out = new PrintWriter(res....
PreparedStatement详细用法
ResultSet resultSet = preparedStatement.executeQuery (); if(!resultSet.next()) occupied=false; preparedStatement.close (); ConnDB.terminate(); } catch(SQLException e){ e.printStackTrace(); ...
Statement st=con.createStatement(); //获取PreparedStatement对象 ResultSet rs=st.executeQuery(sqlStr); //执行查询 String name,sex,email; //查询结果 int age; System.err.println("更新前数据...
主要介绍了详解Java的JDBC中Statement与PreparedStatement对象,PreparedStatement一般来说比使用Statement效率更高,需要的朋友可以参考下
关于PreparedStatement插入Date类型值的方法.txt
7.关闭连接 `ResultSet 、Statement 、Connection` 3.SQL注入问题与解决(Statement 、PreparedStatement) 3.1.模拟SQL注入 3.2.PreparedStatement解决 3.3.Statement 与 PreparedStatement 4.完整源码