Java 中关闭数据库连接
我的数据库类中有以下方法,它返回给定 SQL 语句的结果集:
public static ResultSet sqlStatement(String query) throws SQLException{
ResultSet result = null;
Connection conn = connect();
Statement newStatement = conn.createStatement();
result = newStatement.executeQuery(query);
conn.close();
return result;
}
我想在返回结果集之前关闭与数据库的连接,但它会抛出以下异常:
java.sql.SQLException: out of memory
我是一个 java 菜鸟,正在尝试任何非常感谢您的帮助。
I have the following method in my database class that returns a resultset for a given SQL statement:
public static ResultSet sqlStatement(String query) throws SQLException{
ResultSet result = null;
Connection conn = connect();
Statement newStatement = conn.createStatement();
result = newStatement.executeQuery(query);
conn.close();
return result;
}
I want to close the connection to the database before i return the resultset but it throws the following exception:
java.sql.SQLException: out of memory
I'm a java noob and experimenting so any help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据我过去的经验(没有文档或任何东西),我会像 C 中的指针一样理解“ResultSet”。我敢打赌,当您执行查询时,它会缓存数据库中的一些行。
因此,如果您关闭连接,然后尝试使用结果集,所有这些缓存的结果集没有正确的信息并获取下一个缓存等。因此,它会抛出内存不足异常..
无论如何在java中使用这些结果集的正确方法..
希望它会有所帮助
In my past experience(No document or anything), I would understand the "ResultSet" like a pointer in C. I bet it would cache some rows from database when you execute your query..
Therefore, if you close connection and then try to use resultset, all those cached resultset does not have proper information and getting next cache etc. As a result, it would throw out of memory exception..
Anyway proper way to use those in java..
Hope it would help
将
conn.close()
放在finally
块中,以便在抛出异常时获得执行事件。Put the
conn.close()
in afinally
block so that it gets executed event if an exception is thrown.总是,总是,总是在finally块中关闭数据库资源!
我怀疑你的逻辑是否会按原样工作。 ResultSet 仅在连接打开时可用。在关闭连接之前,您需要处理整个结果集。
always, always, always close your database resources in a finally block!
i doubt your logic will work as is. a ResultSet is only usable while the connection is open. you need to process the entire ResultSet before you close the connection.
除了关闭 finally 块中的资源之外,您还必须关闭
PreparedStatement
和ResultSet
。事实上,您不应该返回ResultSet
并保持它打开太久。相反,您可以将其读入某种中间数据存储,例如List
。另一方面,您没有收到
java.lang.OutOfMemoryError
,因此可能是您的数据库本身内存不足Apart from closing resources in a finally block, you also have to close your
PreparedStatement
and yourResultSet
. In fact, you shouldn't return theResultSet
and keep it open for too long. Instead, you could read it into some sort of intermediary data store, such as aList<Object[]>
.On the other hand, you're not getting a
java.lang.OutOfMemoryError
, so possibly it's your database itself that ran out of memory