当我想返回ResultSet时,在何处关闭JDBC连接 [英] Where to close a JDBC Connection while I want to return the ResultSet

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

问题描述

看来当我关闭 Connection 时, ResultSet 会自动关闭。
但是我想返回 ResultSet 并在另一个方法中使用它,那么我不知道在哪里关闭 Connection PreparedStatement

It seems that the ResultSet will be automatically closed when I close the Connection. But I want to return the ResultSet and use it in another method, then I don't know where to close Connection and PreparedStatement.

public ResultSet executeQuery(String sql, String[] getValue)
{
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try
    {
        conn = getConn();
        pstmt = conn.prepareStatement(sql);
        if (getValue != null)
        {
            for (int i = 0; i < getValue.length; i++)
            {
                pstmt.setString(i + 1, getValue[i]);
            }
        }
        rs = pstmt.executeQuery();
    } catch (Exception e)
    {
        e.printStackTrace();
        closeAll(conn, pstmt, rs);
    }
    return rs;
}



我移动了 closeAll(conn,pstmt, null); into catch块,因为我发现如果我把它放在finally块我会立即失去我的 rs
现在当我想关闭 rs 时,我无法关闭 conn pstmt 。有没有解决方案?

I've moved closeAll(conn, pstmt, null); into catch block because I found that if I put it in finally block I'll lost my rs immediately just before it returns. Now when I want to close the rs, I can't close the conn and pstmt. Is there any solution?

推荐答案

使用 CachedRowSet

Connection con = ...
ResultSet rs = ...

CachedRowSet rowset = new CachedRowSetImpl();
rowset.populate(rs);

con.close()

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

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