| Author |
I need advice on closing connection and stmt after use
|
raminaa niilian
Ranch Hand
Joined: Jul 14, 2005
Posts: 550
|
|
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
internet detective
Marshal
Joined: May 26, 2003
Posts: 26173
|
|
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.
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Emanuel Kadziela
Ranch Hand
Joined: Mar 24, 2005
Posts: 186
|
|
|
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
Joined: Sep 29, 2002
Posts: 1683
|
|
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).
|
SCJP 1.4, SCWCD 1.3, SCBCD 1.3
|
 |
 |
|
|
subject: I need advice on closing connection and stmt after use
|
|
|