复制 Java 结果集
我有一个需要更新的 java.sql.ResultSet 对象。但是结果集不可更新。不幸的是,这是对我正在使用的特定框架的限制。
我在这里想要实现的是从数据库中获取数据,然后操作少量数据,最后将数据写入 CSV 文件。
在这一阶段,我认为最好的选择是创建一个新的结果集对象,并将原始结果集的内容复制到新结果集中,同时操作数据。
然而,我在谷歌上到处搜寻,似乎无法确定如何做到这一点,或者是否有可能。
我对 Java 的一切都很陌生,因此我们将不胜感激。
I have a java.sql.ResultSet
object that I need to update. However the result set is not updatable. Unfortunately this is a constraint on the particular framework I'm using.
What I'm trying to achieve here is taking data from a database, then manipulating a small amount of the data and finally the data is being written to a CSV file.
At this stage I think my best option is to create a new result set object and copy the contents of the original result set into the new one, manipulating the data as I do so.
However, I've hunted high and low on Google and don't seem to be able to determine how to do this or whether it's even possible at all.
I'm new to everything Java so any assistance would be gratefully received.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢您的回复。最后我找到了 CachedRowSet ,这正是我所需要的。这样我就能够断开 ResultSet 对象的连接并更新它。
此外,由于 CachedRowSet 实现了 ResultSet 接口,我仍然能够将其传递给需要实现 ResultSet 的对象的文件生成方法。
Thanks for the responses. In the end I found
CachedRowSet
which is exactly what I needed. With this I was able to disconnect theResultSet
object and update it.What's more, because
CachedRowSet
implements theResultSet
interface I was still able to pass it to my file generation method which requires an object that implements ResultSet.通常的做法是将
ResultSet
映射到List
,其中Entity
是您自己的类,其中包含有关由单个数据库行。例如用户
、人员
、地址
、产品
、订单
等,具体取决于表中实际包含的内容。然后,您可以按照通常的Java方式访问、遍历和修改它。最后,当将其持久化回数据库时,使用PreparedStatement一次性批量更新它们。
请注意,某些数据库对批量大小有限制。 Oracle 的 JDBC 驱动程序对大约 1000 个项目有限制。然后,您可能需要每 1000 个项目调用一次
executeBatch()
。在循环内使用计数器应该很简单。另请参阅:
The normal practice would be to map the
ResultSet
to aList<Entity>
whereEntity
is your own class which contains information about the data represented by a single database row. E.g.User
,Person
,Address
,Product
,Order
, etcetera, depending on what the table actually contains.Then, you can access, traverse and modify it the usual Java way. Finally, when persisting it back in the DB, use a
PreparedStatement
to update them in batches in a single go.Note that some DB's have a limit on the batch size. Oracle's JDBC driver has a limit on around 1000 items. You may want to call
executeBatch()
every 1000 items then. It should be simple using a counter inside the loop.See also: