File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes open database connection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "open database connection" Watch "open database connection" New topic

open database connection

tarun Mehra

Joined: May 30, 2001
Posts: 12
I am using a number of servlets that connect to a database using another class x. The code for opening the database connection is in the constructor of class x. So everytime the servlets are loaded an instance of this class x is created and the database connection is opened. My question is how do I ensure that the resources are released at the end or is it alright to leave the database connection open. One of my thoughts was to close the connection in the finalize() method of the class x but that does not happen.
Your help will be greatly appreciated.
Thank you,
Sonny Pondrom
Ranch Hand

Joined: Jun 05, 2001
Posts: 128
I have not used serlets yet, but in a class where I connect to an Excel database, after I get my answers, I close my SQL statement and the connection.
I am connecting only once, maybe that is why I am not having any problems.
Sean MacLean
Ranch Hand

Joined: Nov 07, 2000
Posts: 621
One solution would be to create a DataBase utility class that contains a static initilaizer in which you load the DB drivers and open a connection. This way, the DB connection will only be created once when the utiliy class is loaded. Now the class that you currently have can simply as the Utility class to give it a connection (using a static method, of course). Something like this:

An added benefit here is that the utility method can change to load different drivers or even to maintain a pool of connections and the rest of the application won't even be aware. I hope this helps.
wood burning stoves
subject: open database connection
It's not a secret anymore!