This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes JDBC and Relational Databases and the fly likes try..catch block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "try..catch block" Watch "try..catch block" New topic

try..catch block

Yuan Ye
Ranch Hand

Joined: Mar 05, 2003
Posts: 172
This is a question I have for a long time. For a db access method, normally we have the structure of:

Is there a way to clean up th code for the last catch block which is for the db clean up exception? Or do I have to write such block in each db call?
[ April 21, 2006: Message edited by: Yuan Ye ]
stu derby
Ranch Hand

Joined: Dec 15, 2005
Posts: 333
If the "db cleanup" is the same, put all that finally stuff in a static class.
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 32818

A common approach is to create a DBUtils class that has the common code in a static method. Then you can pass the connection/statement/resultset into that method. So one call is repeated instead of a bunch of code.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Mattias Arthursson
Ranch Hand

Joined: Jul 26, 2004
Posts: 90
Another common solution to avoid writing the same dull jdbc code over and over is to use Spring JDBC, a part of the Spring framework. It neatly encapsulates all of the plumbing (connection management, exception handling, looping through result sets, resource cleanup etc.) and lets you focus on the important stuff.

Admit nothing. Blame everyone. Be bitter.
jQuery in Action, 3rd edition
subject: try..catch block
It's not a secret anymore!