Java – Is statement.close() explicitly required in connection pooled environment

connection-poolingjavajdbcsql

I am using connection pooling in my application. My question is:

Is it explicitly required to close statement before closing connection in case of connection pooled environment?

In connection pooled environment connection is not getting closed, (but returns back to free connection pool).
I had checked jdbc 4.0 functional specs. In point number 9.4.4, it clearly states that :

Closing Connection Objects An application calls the method Connection.close to indicate that it has finished using a connection. All Statement objects created from a given Connection object will be closed when the close method for the object is called. Once a Connection has been closed, any attempt to access any of its methods with the exception of the close, isClosed or isValid methods will result in a SQLException being thrown.

So jdbc specs mandates closing all statement at a time of closing connection. So is it applicable to only non connection pooled environment only or it applies to connection pooled environment also ?

According to me it should not matter in case of pooled environment, because we are coding for interface (java.sql.Connection & java.sql.Statement). So we are not bothering about implementation and parent class (java.sql.Connection) doesn't have any information about child/impementation class (Vendor implementation class).

Best Answer

Absolutely. It's possible that the Statement implementation will have other resources which should be released, or have some other relationship with the connection. You don't, and shouldn't, know the implementation details.

Your approach is absolutely right: code to the interface and avoid little "short-cuts" which could easily bite you later. (Even if it works now, it might not in a future version of the pool or connection classes.)

Related Topic