This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JDBC and the fly likes Is connection.close(); enough? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Is connection.close(); enough?" Watch "Is connection.close(); enough?" New topic
Author

Is connection.close(); enough?

Richard Bell
Greenhorn

Joined: Oct 20, 2011
Posts: 4

When using a data source to access a database is "connection.close();" going to close the associated statement and resultSet?

I have read a number of articles posted on a number of sites,
almost all agree that it is good practice to close the resultSet, statement and connection individually.
I have also read that the JDBC specification details that closing the connection will also close any associated resources (resultSet and statements).
There does not seem to be a right or wrong answer.

So would code closing just the connection be appropriate or should we always close all three?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

Closing the connection will close the (prepared / callable) statements and result sets. However, depending on the application, there may be a long time between no longer needing the statements and result sets and closing the connection. All this time, these resources will still be active. This can lead to a huge memory leak (especially with larger result sets) and failure to create statements later if the maximum number is reached. So yeah, close everything as soon as you're done with them. Preferably, use try-with-resources:
Likewise for ResultSet. You can even combine the two:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
jQuery in Action, 2nd edition
 
subject: Is connection.close(); enough?
 
Similar Threads
Statement, ResultSet
SQL Exception?
A[nother] question about tracking down memory leaks
timeout error
ResultSet.close() Vs Connection.close()