如何防止结果集在连接关闭时失效?

发布于 2024-09-29 00:55:29 字数 190 浏览 0 评论 0原文

我想从执行查询并关闭连接的函数传递结果集。

但是,一旦其父 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

虚拟世界 2024-10-06 00:55:29

你不能。如果您想获取所有数据,请循环 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.

金橙橙 2024-10-06 00:55:29

另请考虑使用断开连接的结果集: <代码>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.

夕色琉璃 2024-10-06 00:55:29

你想要彻底改变你的想法!

创建一个对 ResultSet 执行某些操作的函数,
并将其作为闭包传递到运行查询的函数中。

def withQuery[T](query:String)(template: ResultSet => T) : T = {
  val resultSet = runQuery(query)
  val ret = template(resultSet)
  resultSet.close
  ret
}

val output = withQuery("select * from ...") {
  resultSet =>
  //some expression that generates a string from the resultset
}

println(output)

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.

def withQuery[T](query:String)(template: ResultSet => T) : T = {
  val resultSet = runQuery(query)
  val ret = template(resultSet)
  resultSet.close
  ret
}

val output = withQuery("select * from ...") {
  resultSet =>
  //some expression that generates a string from the resultset
}

println(output)
久隐师 2024-10-06 00:55:29

这不是 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 ResultSets keep a list of the ones it has given out. Each piece of code that uses the ResultSet can call close() 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 (using isClosed()), and if so, close the connection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文