连接关闭时ResultSet未关闭? [英] ResultSet not closed when connection closed?

查看:190
本文介绍了连接关闭时ResultSet未关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在对我们的某个宠物项目进行代码审查(主要使用像FindBugs这样的工具),而FindBugs将以下代码标记为错误(伪代码):

I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode):

Connection conn = dataSource.getConnection();

try{
    PreparedStatement stmt = conn.prepareStatement();
    //initialize the statement
    stmt.execute();
    ResultSet rs =  stmt.getResultSet();
    //get data
}finally{
    conn.close();
}

错误是此代码可能无法释放资源。我发现ResultSet和Statement没有关闭,所以我最后关闭了它们:

The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally:

finally{
    try{
        rs.close()
    }catch(SqlException se){
        //log it
    }
    try{
        stmt.close();
    }catch(SqlException se){
        //log it
    }
    conn.close();
}

但我在很多项目中遇到过上述模式(来自不少公司) ,并且没有人关闭结果集或声明。

But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements.

在Connection关闭时,您是否遇到没有关闭ResultSet和Statements的麻烦?

Did you have troubles with ResultSets and Statements not being closed when the Connection is closed?

我发现只有这个它指的是Oracle在关闭Connections时关闭ResultSet的问题(我们使用Oracle db,因此我的更正)。 java.sql.api在Connection.close()javadoc中没有说什么。

I found only this and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.

推荐答案

仅关闭连接而不是关闭连接的一个问题结果集,如果您的连接管理代码使用连接池, connection.close()只会将连接放回池中。此外,某些数据库在服务器上有一个游标资源,除非明确关闭,否则不会正确释放。

One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the connection.close() would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it is explicitly closed.

这篇关于连接关闭时ResultSet未关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆