I have a Servlet that calls another class file where I am choosing one of several different database actions. I am connecting to the database several times in the class file and I assume there is a better more efficient way of doing this?
The below is only showing 2 out of 4 methods where I am showing dataHit and dataInsert methods. The other methods I left out (for space reasons in this post) are dataUpdate and dataDelete methods.
Please advise. [ September 19, 2006: Message edited by: Mike Jenkins ]
1) Eliminate redundant code 2) Don't hard code user name, password, driver and url 3) Put resource 'closes' in finally block 4) Don't gobble exceptions and simply write them to a log. 5) Give your methods more meaningful names than 'dataHit'
If you want to be efficient with database connections, and other object you will be using, or need performance plan in advance for that.
What I mean is if you know that a certain operation is going to take 2 or 3 calls to methods that will have to close and reopen the connection in sequence you may/will be better off performing all of this in one single method. The catch here is that you will have code redundancy if you do not plan it out properly. You may consider using a connection pool as then you can keep closing and opening but your performance will not suffer substantially. You can also encapsulate the actual method sequence and open and close your Connection there something of a Template method.
Having one spot for performing common operation closing objects, is good too, as you do not have to make many changes in different places in your code, for logging etc., and can easily change the way you handle things at a later point in time. I used to close my stuff in the general fashion in the method and copy that over and over again and then I would find myself troubleshooting a bigger problem with connection leaks and would have to recode a bunch of statement all over the place. Sometime after that incident, I saw someone using a method to close connections and have been doing it ever since. Thank God for open source and forums like this one ;)