Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC Closing Resources

I am unsure whether a statement and resultset should be closed after each query or after all my queries have been made (ie at the same time i close the connection)?

Correct me if I'm wrong, but I'm pretty sure both work?

However, would the database eventually crash if I didn't close a statement after each query and then performed a lot of queries?

On the other hand, would it be inefficient and time-wasting to keep closing & creating statements for every query?

I've read up a lot on this problem before asking this question, but I'm still uncertain. Any help appreciated,

tre.

like image 474
tre Avatar asked Jun 11 '26 13:06

tre


1 Answers

From http://www.precisejava.com/javaperf/j2ee/JDBC.htm#JDBC118:

Close ResultSet when finished

Close ResultSet object as soon as you finish working with ResultSet object even though Statement object closes the ResultSet object implicitly when it closes, closing ResultSet explicitly gives chance to garbage collector to recollect memory as early as possible because ResultSet object may occupy lot of memory depending on query.

In a nutshell, you don't have to explicitly close your ResultSet objects, but it's better to do so to free up memory earlier on. Failing to close your ResultSet objects will just cause the memory that it occupies (which can be small, or large, depending on the size of the result set) to be occupied until the corresponding Statement object is closed.

like image 104
Mansoor Siddiqui Avatar answered Jun 13 '26 01:06

Mansoor Siddiqui