Java Utility for JDBC
Code re-usability is one of the many benefits of object oriented programming. For example, in Java if you need to perform email validation in different classes, rather than writing validation code in each class you can create email validation method in one class and then call that method from other classes. Now you have only one piece of code for email validation which is easy to maintain.
Similarly with JDBC, every time you need to access database you have to do following steps:
- Create connection to database
- Create statment
- Execute statement
- Loop through the ResultSet
- Close connection
- Handle exceptions
Often you create the “where” clause of your SQL statement dynamically based on the values of your local variables. In any project that involves database queries this code may be repeated dozens of time if not more.
In an attempt to reduce JDBC code I developed a utility class that performs these JDBC steps. Now when I need to retrieve data from database I call one of the methods in my DatabaseUtility class. I don’t have to create connection or build query statments. I just call the utility class’ method to get data from any table even if don’t know the column names and their datatypes. All I need is the table name!
You can see an example here.
The class with javadoc in zip format is available here.
Feel free to use it in your applications.
Contact me if you want the source code or need help in using this class.