如何防止结果集在连接关闭时失效?
我想从执行查询并关闭连接的函数传递结果集。
但是,一旦其父 Connection 关闭,ResultSet 就会失效并抛出异常
java.sql.SQLException: Operation not allowed after ResultSet closed
如何避免这种情况?
I'd like to pass out a result set from a function that executes a query and closes the connection.
But the ResultSet gets invalidated as soon as its parent Connection is closed and throws
java.sql.SQLException: Operation not allowed after ResultSet closed
How to avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能。如果您想获取所有数据,请循环
ResultSet
并将数据插入到您的集合中。看看 commons-dbutils - 它有很多有用的帮助器。
You can't. If you want to get all the data, loop the
ResultSet
and insert the data into a collection of yours.Take a look at commons-dbutils - it has a lot of useful helpers.
另请考虑使用断开连接的结果集: <代码>CachedRowSet。快速谷歌搜索给了我这个: Using CachedRowSet to Transfer JDBC Query Results Between Classes 。
Also consider using a disconnected result set:
CachedRowSet
. Quick googling gave me this: Using CachedRowSet to Transfer JDBC Query Results Between Classes.你想要彻底改变你的想法!
创建一个对 ResultSet 执行某些操作的函数,
并将其作为闭包传递到运行查询的函数中。
You want to turn your thinking inside out!
Create a function that will do something with the ResultSet,
and pass it as a closure into the function that runs the query.
这不是 ResultSet 的工作原理。它本身不存储数据,它只是充当数据的接口。
您可以尝试的是让返回 ResultSet 的类保留它已给出的结果集的列表。使用 ResultSet 的每段代码在使用完毕后都可以对其调用
close()
。然后第一个类可以检查所有已给出的 ResultSet 是否已关闭(使用 isClosed() ),如果是,则关闭连接。That's just not how ResultSet works. It doesn't store the data itself, it just acts as an interface to it.
What you could try instead is having the class that's returning the
ResultSet
s keep a list of the ones it has given out. Each piece of code that uses the ResultSet can callclose()
on it when it's done with it. Then the first class can check if all ResultSets that have been given out have been closed (usingisClosed()
), and if so, close the connection.