重用ResultSet [英] Reusing ResultSet

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

问题描述

我需要连续运行几个查询

I need to run several queries in a row

Statement st = cnx.createStatement();
ResultSet rs = st.executeQuery( "SELECT [good stuff]");
// do something smart with rs
rs = st.execute( "SELECT [better stuff]");
// do something smarter with rs
rs = st.execute( "SELECT [best stuff]");
// you got it
try{ rs.close();} catch( SQLException ignore){};
try{ st.close();} catch( SQLException ignore){};

这是前两个ResultSet未正确关闭还是在垃圾回收期间隐式完成的问题?

Is this a problem that the first two ResultSet are not properly closed or is it implicitely done during garbage collection?

推荐答案

在执行第二个查询后,上一个ResultSet将自动关闭.就Garbage Collection而言,您不必担心.您仅可以在最后加上stmt.close()即可.它将自动关闭所有相关的ResultSet对象.

As soon as you execute the 2nd query, the previous ResultSet is automatically closed. And as far as Garbage Collection is concerned, you don't have to worry about that. You can just have a stmt.close() at the end that's all. It will automatically close all the related ResultSet objects.

看看:- ResultSet#close 文档,其中说:-

Take a look at : - ResultSet#close documentation, which says that: -

一个ResultSet对象被Statement对象自动关闭 当该Statement对象关闭,重新执行, 或用于从多个序列中检索下一个结果 结果.

A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.

如果要测试,是否关闭结果集,可以使用while循环遍历result set,并在while循环内部,创建另一个查询并将其分配给相同的结果集.您将看到将引发异常..

If you want to test, whether your resultset gets closed or not, you can use a while loop to iterate over the result set and inside the while loop, create another query and assign it to same result set. You will see that an Exception will be thrown..

ResultSet res = stmt.executeQuery("SELECT * FROM sometable");

while (res.next()) {
    res.getString(1);

    // Closes the previous `ResultSet`
    res = stmt.executeQuery("SELECT * FROM othertable");
} 

因此,在上面的代码中,在第二次迭代中,您将得到一个Exception: - Cannot perform operation after ResultSet is closed

So, in the above code, on the 2nd iteration, you will get an Exception: - Cannot perform operation after ResultSet is closed

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

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