Builder http://builder.com.com Presents your JAVA E-NEWSLETTER for October 31, 2002 <-------------------------------------------> MAKE JDBC EASIER TO LIVE WITH Dealing with JDBC often involves a lot of repeated code and numerous catching of SQLExceptions. These complications make it worth the trouble of putting together a JDBC Util class which can be reused across the codebase. Util classes contain lots of static methods that help with development of an area. So a StringUtil class would contain a capitalize method, and a StreamUtil class might contain a pushStream class for reading everything from an input stream and writing it to an output stream. There are two decisions that need to be made when creating such a set of standard utilities. First, you must decide what functionality is desired. Then you must decide what kind of logging should be done. The second is harder, with the decision revolving around whether the Util class should use System.err, throw new Exceptions, quietly hide errors, or use a logging class such as log4j. With the release of JDK 1.4, we'll all be using the java.log package, so this should become an easier question to answer. For the following examples, we'll output any errors to System.err. One desired functionality for a JDBC Util is an ensureLoaded method. When handling JDBC code, it is common to require that the particular driver class you wish to use be loaded into memory before you can start to make SQL calls. This is nicely achieved by calling JdbcUtil.ensureLoaded(String driverName). Note that a JDBC Util class is named JdbcUtil in accordance with the Sun Java coding standard that says that acronyms in class names should not be all capitalized. JdbcUtil.ensureLoaded would look like: static public boolean ensureLoaded(String name) { try { Class.forName(name).newInstance( ); return true; } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace( ); return false; } catch(IllegalAccessException iae) { iae.printStackTrace( ); return false; } catch(InstantiationException ie) { ie.printStackTrace( ); return false; } } For Oracle, JdbcUtil.ensureLoaded would be called with: JdbcUtil.ensureLoaded("oracle.jdbc.driver.OracleDriver"); Another piece of generic functionality might be functions to turn a ResultSet into an Object array, to get the column names from a ResultSet, to get the column type for a particular column, or to get the primary key names for a table. A common set of Util classes can enhance development tremendously, the most important thing to remember though is not to stick them all in Util.java. ----------------------------------------