resultset 在数据库连接断开后是否可以被使用

来源:互联网 发布:node实现反向代理跨域 编辑:程序博客网 时间:2024/04/30 11:21

在Connection上调用close方法会关闭Statement和ResultSet吗?

级联的关闭这听起来好像很有道理,而且在很多地方这样做也是正确的,通常这样写
Connection con = getConnection();//getConnection is your method
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
……
///rs.close();
///ps.close();
con.close(); // NO!
这样做的问题在于Connection是个接口,它的close实现可能是多种多样的。在普通情况下,你用DriverManager.getConnection()得到一个Connection实例,调用它的close方法会关闭Statement和ResultSet。但是在很多时候,你需要使用数据库连接池,在连接池中的得到的Connection上调用close方法的时候,Connection可能并没有被释放,而是回到了连接池中。它以后可能被其它代码取出来用。如果没有释放Statement和ResultSet,那么在Connection上没有关闭的Statement和ResultSet可能会越来越多,那么……
相反,我看到过这样的说法,有人把Connection关闭了,却继续使用ResultSet,认为这样是可以的,引发了激烈的讨论,到底是怎么回事就不用我多说了吧。(作者意思是:rs的资源没有释放,还用的是连接池中的conn)

所以我们必须很小心的释放数据库资源,下面的代码片断展示了这个过程

Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
con = getConnection();//getConnection is your method
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
///...........
}
catch (SQLException ex) {
///错误处理
}
finally{
try {
if(ps!=null)
ps.close();
}
catch (SQLException ex) {
///错误处理
}
try{
if(con!=null)
con.close();
}
catch (SQLException ex) {
///错误处理
}
}
很麻烦是不是?但为了写出健壮的程序,这些处理是必须的。

大意如下:

如果不使用连接池机制, 关闭connection, 必然关闭resultset!
如果使用连接池, 所谓的关闭connection, 其实是将连接返回给了连接池,
连接对象依然存在, 所以这实际上不叫关闭!
2。Iterator aaItr= bbList.iterator();
Iterator是JAVA中集合的内容 
有些书上又叫重复器或是迭代器, 
Iterator aaItr中放的应该是bbList中所有的值 
应该是bbList的一个幅本 
原创粉丝点击