Hello, 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, tarun
Joined: Jun 05, 2001
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.
Joined: Nov 07, 2000
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. Sean