Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to close db connection

 
malik ge
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
malik ge
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't get what you meant by
do con.close(); for every action, not method.
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 68
Firefox Browser Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic