0

JDBC: What resources you have to close and when?

 2 years ago
source link: https://blog.jakubholy.net/2013/02/18/jdbc-what-resources-you-have-to-close-and-when/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JDBC: What resources you have to close and when?

February 18, 2013
I was never sure what resources in JDBC must be explicitely closed and wasn't able to find it anywhere explained. Finally my good colleague, Magne Mære, has explained it to me:

In JDBC there are several kinds of resources that ideally should be closed after use.  Even though every Statement and PreparedStatement is specified to be implicitly closed when the Connection object is closed, you can't be guaranteed when (or if) this happens, especially if it's used with connection pooling. You should explicitly close your Statement and PreparedStatement objects to be sure. ResultSet objects might also be an issue, but as they are guaranteed to be closed when the corresponding Statement/PreparedStatement object is closed, you can usually disregard it.

Summary: Always close PreparedStatement/Statement and Connection. (Of course, with Java 7+ you'd use the try-with-resources idiom to make it happen automatically.)

PS: I believe that the close() method on pooled connections doesn't actually close them but just returns them to the pool.

A request to my dear users: References to any good resources would be appreciate.

Are you benefitting from my writing? Consider buying me a coffee or supporting my work via GitHub Sponsors. Thank you! You can also book me for a mentoring / pair-programming session via Codementor or (cheaper) email.

Allow me to write to you!

Let's get in touch! I will occasionally send you a short email with a few links to interesting stuff I found and with summaries of my new blog posts. Max 1-2 emails per month. I read and answer to all replies.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK