Reputation: 1322
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.
Upvotes: 1
Views: 7549
Reputation: 548
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..
Connection con...
try{
create connection
execute query
use your resultset completely..
}catch(...){
}finally{
close connection;
}
Hope it would help
Upvotes: 2
Reputation: 221195
Apart from closing resources in a finally block, you also have to close your PreparedStatement
and your ResultSet
. In fact, you shouldn't return the ResultSet
and keep it open for too long. Instead, you could read it into some sort of intermediary data store, such as a List<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
Upvotes: 0
Reputation: 53694
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.
Upvotes: 1
Reputation: 8283
Put the conn.close()
in a finally
block so that it gets executed event if an exception is thrown.
Upvotes: 1