Reputation: 2999
Would there be any effect if I close my Connection
object once I got my ResultSet
?
Connection con= DriverManager.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
con.close();
Further to this I use my rs
object and I feel there will not be any impact on it. Because ResultSet
and Statement
are in connection with each other.
Upvotes: 2
Views: 1095
Reputation: 172
You can't access the resultset soon after you close the connection to the database. Because, when you use resultset.next()
method, it will send a request to the database in order to fetch the next record; but physically the connection has been closed. So, an Exception
will be thrown by your statement resultset.next()
.
Upvotes: 3
Reputation: 485
You mustn't use anything derived from a Connection
after the connection is closed.
This is actually because things like Result Sets might not be transferred to your machine until you actually use them. Databases can and do use transfer batching and server cursors - which is a complicated way of saying they only transfer a block of rows to you as you actually request them by moving the result set cursor (for instance with ResultSet#next()
).
Other parts of the result set, like BLOB or other LOB types, aren't transferred at all until you actually read them out of the result set. That's because they can be arbitrarily large and the DB driver (okay, a good DB driver) wants to minimize the memory it uses in the client.
The DB server itself is usually vastly more sophisticated than the driver (which becomes little more than a communications arbiter), and it's best to leave the 'heavy lifting' (marshalling and temporary storage of result sets) to the DB :-)
So you can see that closing a connection is going to free all the server resources - and there could be many - associated with your query.
Upvotes: 3
Reputation: 25873
You cannot close the connection if you want to access the ResultSet
after closing. You will lose the ResultSet
data and will get an exception when you try to access it.
This is because ResultSet
instances are linked to the DB connection.
Upvotes: 2
Reputation: 13872
Once the Connection
is closed other resources (Statement
s or ResultSet
s) must not be used.
Upvotes: 3