所以我在 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, aCachedRowSet
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 disconnectedRowSet
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/