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

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

问题描述

当我关闭 Connection 时,似乎 ResultSet 会自动关闭.但是我想返回 ResultSet 并在另一个方法中使用它,然后我不知道在哪里关闭 ConnectionPreparedStatement.

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); 移动到 catch 块中,因为我发现如果我将其放入 finally 块中,我将丢失我的 rs就在它返回之前.现在当我想关闭 rs 时,我无法关闭 connpstmt.有什么解决办法吗?

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天全站免登陆