Does closing Connection automatically close statement and resultset?

Srujan Kumar Gulla picture Srujan Kumar Gulla · Dec 24, 2012 · Viewed 23.8k times · Source

I know the safe pattern in Java is to close your ResultSet, Statement, and Connection in order in a finally block.

If you close connection and then try to close statement(doesnt throw exception). But if you try to call any method from statement an exception is thrown.

I was wondering does closing connection automatically close all the statement objects created out of that connection?

Update:
I am using DatabaseProductVersion: Oracle Database 11g Release 11.1.0.0.0
DriverName: Oracle JDBC driver
DriverVersion: 10.2.0.4.0

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Dec 24, 2012

Yes it does, Connection.close API says "Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released". The problem is that applications typically use database connection pools and these may simply return Connection to pool on Connection.close.

In any case, it's a good practice to always close ResultSet and Statement explicitly and not to rely on Connection.close.

Besides, it's not the best idea to work with JDBC directly. You can use Spring JDBC instead and forget about releasing resources problem.