java - 如何在 SQL Wrapper 类中返回 ResultSet

标签 java mysql

所以我在 Java 中创建了一个简单的 MySQL 包装器类,只是为了我个人的易用性,尽管我有一个问题。

在 Java 中的每个 MySQL 示例中,ResultSet 关闭,然后是 Statement,然后是 Connection。这个顺序重要吗?如果不重要,是否必须关闭 ResultSet

我想返回结果集,但如果我不能这样做,我必须找到其他方法来返回查询结果。

最佳答案

Is order important?

是的,一般来说,以相反的顺序关闭资源是一种很好的做法。同样在 Java 7 try-with-resources 中,顺序是相反的,即最后打开的资源首先关闭。

Passing result set to other components?

您可以使用 CachedRowSet为此,它是一个与数据源断开连接的结果集,可以安全地传递给其他组件。

引用 Oracle javadocs:

A CachedRowSet object is a disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA).

编辑:

基于@JoD 的评论。在选择任何选项之前,您应该考虑数据大小和您要解决的问题。

If you are handling a query, maybe as part of an ETL job, that needs to handle 4 GB of memory, do you really want to have that 4GB completely in memory before you start any further processing? CachedRowSet is very good given certain situation, and is definitely worth mentioning here. But we should consider this in the proper context

关于java - 如何在 SQL Wrapper 类中返回 ResultSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041077/

相关文章:

java - 使用项目作为库,但需要更改 contentView

java - 不使用构造函数获取子类的 java.lang.Class 实例

java - 如何将我的状态机转换为 java?

java - SQLite 'Database Locked' 特定查询的奇怪错误

php - 需要一些有关通过 CSV 导入订单的 Mysql 帮助和建议

PHP - 与父级一起创建评论列表

java - 如何使用 BufferedWriter 将二维数组保存到文本文件中?

mysql - 最近 4 个和即将到来的 4 个生日

mysql - mybatis mapper中sql保存emoji失败

php - CodeIgniter - 按月订购我的 'posts'?