File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JDBC and the fly likes How to close db connection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "How to close db connection" Watch "How to close db connection" New topic
Author

How to close db connection

malik ge
Ranch Hand

Joined: May 13, 2011
Posts: 69
Hi,
I am making a small application. I have a separate class which inserts or gets the data from database.
I want to know how to close the connection of database?

Should I do con.close(); in every method or closing the connection in finalize() method is sufficient?

Hebert Coelho
Ranch Hand

Joined: Jul 14, 2010
Posts: 754

I would do con.close(); for every action, not method.

If you need to use the database 3 times for an action you would open and close just once. If you do 3 times your performance will decrease.


[uaiHebert.com] [Full WebApplication JSF EJB JPA JAAS with source code to download] One Table Per SubClass [Web/JSF]
malik ge
Ranch Hand

Joined: May 13, 2011
Posts: 69
I didn't get what you meant by
do con.close(); for every action, not method.
Hebert Coelho
Ranch Hand

Joined: Jul 14, 2010
Posts: 754

malik ge wrote:I didn't get what you meant by
do con.close(); for every action, not method.


Let us supose you have a method that will create a customer, a car and a house.

An action would be something like:

openConnection();
createCustomer(customer);
createCar(customer);
createHouse(customer);
closeConnection();

An action would be like group of methods.
Philip Grove
Ranch Hand

Joined: Aug 18, 2009
Posts: 68

Splitting the con.close() invocation out into its own method gives the risk of forgetting to invoke that method, but at the same time opening and closing the connection provides overhead so doing it as few times as possible is generally a good idea.

Do not use the finalize() method for housekeping. They are meant for objects holding native resources, and while a connection is a native resource there is also no guarantee that they will ever run.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to close db connection
 
Similar Threads
SQL syntax error
NullPointerException - connecting it mySQL
Could not locate DB driver
problem in servlet to jsp
NullPointerException on getServletContext