Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I need advice on closing connection and stmt after use

 
raminaa niilian
Ranch Hand
Posts: 551
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Thank you for reading my post.
I want to know , how and where i should close statement ,PreparedStatement, Connection that i use in my source code.

imagine that i have a try catch block , so inside Try i create the connection , statement ,...
I do all my jobs here. if my source code execution face any exception it will goes to catch block , so it is very likely that i did not closed my connection ,....


if i try to close them i catch block , then i need another try catch for them

if i try to close them in finally block then i will need another try/catch block there.....

where and how i should close statement and connections ?
does closing statement close the connection too and vice-versa ?

in case that i use a connection pool , *must* i close a connection or it will be closed after i exit the scope(method) that i made the connection inside it ?


Thank you very much.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35266
383
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by raminaa niilian:
i try to close them in finally block then i will need another try/catch block there.....

This is the one. You close them in a finally block that has a nested try/catch. That catch should just log the error message. You don't want your program to crash because there was a problem closing a resource.

in case that i use a connection pool , *must* i close a connection or it will be closed after i exit the scope(method) that i made the connection inside it ?

You still must close the connection (which really just returns it to the pool.) Otherwise, you will have a resource leak and the connection pool won't know about all the free connections.
 
Emanuel Kadziela
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One note about connections and pools. Connection creation is generally an expensive process, which is why they get pooled. Pools differ in many respects, but one of them is the way they deal with creating and destroying connections. Some will handle things more automatically then others, so you have to be careful about what you are using and how.
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does closing statement close the connection too and vice-versa ?

Closing a JDBC resource also closes any resource which it created. So, closing a Connection also closes the Statement (which will also close any ResultSet it may have created).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic