developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Career Education
Cell Phones
Data Center Solutions
Remote Online Backup
Memory Upgrades
Online Universities
KVM over IP
GPS
Auto Insurance Quote
PDA Phones & Cases
Car Donations
Desktop Computers
Build a Server Rack
KVM Switch over IP

 


Download these IBM resources today!
e-Kit: IBM Rational Systems Development Solution
With systems teams under so much pressure to develop products faster, reduce production costs, and react to changing business needs quickly, communication and collaboration seem to get lost. Now, theres a way to improve product quality and communication.

Webcast: Asset Reuse Strategies for Success--Innovate Don't Duplicate!
Searching for, identifying, updating, using and deploying software assets can be a difficult challenge.

eKit: Rational Build Forge Express
Access valuable resources to help you increase staff productivity, compress development cycles and deliver better software, fast.

Download: IBM Data Studio v1.1
Effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life.

eKit: Rational Asset Manager
Learn how to do more with your reusable assets, learn how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse.
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

SQLExecutor: A Simple JDBC Framework
By Jeff Smith

Go to page: 1  2  3  Next  

While designing an SQL intensive J2EE application for a client, I decided that I needed to streamline the bloated JDBC code required to execute SQL statements. While JDBC is a powerful, low level API for accessing and manipulating a myriad of SQL databases1, it is so low level that it requires:

  1. Writing verbose finally blocks to close database connections
  2. Writing catch blocks for all checked exceptions, even if they can't be reasonably recovered from. For example, programs typically can't recover from bad SQL grammar or a non-existent view errors—nor should they. So why should programmers be forced to write exception blocks to catch them?
  3. Adding clumsy if else or switch statements that examine SQLState or error code values to determine the type of exception generated
  4. Writing custom connection or connection pooling code

For example, here is some standard JDBC code that selects records from a table and displays them via System.out:

public static void testStandardJDBC()
{
    String sql = "SELECT * FROM JDBC_TEST
                           WHERE TEST_ID < ? AND TEST_DT < ?";
Connection con = null; try { Class.forName(driverName).newInstance();
        con = DriverManager.getConnection(connURL,
                                          username,
                                          password);

        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1, 8);
        ps.setDate(2, Date.valueOf("2003-05-10"));
        ResultSet rs = ps.executeQuery();

        String out = "SQL RESULTS:\n";
        while (rs.next())    //still have records...
          out += rs.getLong("TEST_ID") + " " +
                 rs.getString("NOTES") + " " +
                 rs.getDate("TEST_DT") + " " +
                 rs.getDouble("AMOUNT") + " " +
                 rs.getString("CODE") + "\n";
        System.out.println(out);
} catch (SQLException sqle) { sqle.printStackTrace(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (con != null) con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } }

The only code in this method that is really doing anything useful is the highlighted code. The rest is just JDBC overhead. Even if you can place the code that creates the database connection in another method (or class), you will still be left with bloated code that catches exceptions for which you don't want to write recovery code.

Programmers can live with this awkward limitation of JDBC when they have only one or two sections of JDBC code. But if your JDBC application has code like this in 100 places, you're going to have a lot of superfluous code that can be a breeding ground for unnecessary bugs. A good JDBC framework could eliminate these problems.

I looked at some already existing JDBC frameworks2, 3, 4, but they either didn't provide the exception handling flexibility I wanted or they were overly complicated to use. Rod Johnson's JDBC framework fell into the latter category—excellent in many respects, but it required creating a subclass for each query, learning a somewhat complicated exception hierarchy, and requiring framework users to implement anonymous inner classes. I wanted to create a useful framework for both advanced Java programmers who only have five minutes to learn a new framework, and for beginner/intermediate Java programmers who may find it difficult to understand a more complicated framework.

When I designed the SQLExecutor framework, my primary focus was on creating a very simple interface to the JDBC API. I wanted to minimize the number of classes and methods the framework user needed to learn as well as reduce the number of lines of code required to execute SQL statements. I did not try to complicate the framework by supporting every arcane use of JDBC—there may be instances when you will need to write low-level JDBC code in order to accomplish an unusual task. That said, the framework should successfully execute the vast majority of SQL you throw at it.

Here is the same SELECT statement code using my simple JDBC framework:

public static void testSimpleSelectWithParams()
{
    String sql = "SELECT * FROM JDBC_TEST
                           WHERE TEST_ID < ? AND TEST_DT < ?";
    ConnectionPool conPool = new ConnectionPool(1, driverName,
                                 conURL, username, password);
    SQLExecutor sqlExec = new SQLExecutor(conPool);
    sqlExec.addParam(new Integer(8));
               //add int param with value = 8
    sqlExec.addParam(Date.valueOf("2003-05-10"));
               //add date param with value 5/10/03
    SQLResults res = sqlExec.runQueryCloseCon(sql);
               //runs the query, closes connection
    System.out.println(res.toString());
               //display entire result set in tabular form
}

Note that every line of code is doing something useful. The database connection is abstracted away in the new ConnectionPool() call. There is no code for closing the connection because it is closed automatically in the runQueryCloseCon() method. The programmer isn't required to catch exceptions he doesn't want to handle. Because the framework generates runtime exceptions, the programmer is empowered to either catch recoverable exceptions, or just let the exceptions bubble up to the calling code block. He is not forced to write unnecessary catch blocks.

Another problem inherent in standard JDBC is the difficulty in determining the exact cause of a database exception without resorting to messy if else or switch statements to decipher the database error code. My exception classes provide simple methods such as isNonExistentTableOrView() and isDataIntegrityViolation() to enable the framework user to determine the exact cause of the JDBC failure so he can implement the appropriate recovery strategy. To this end, the abstract exception superclass, DatabaseException, extends the RuntimeException class.

Go to page: 1  2  3  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Database Archives

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Intel Go Parallel Portal: Translating Multicore Power into Application Performance
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Five Trends for Application Development & Program Management. Download Complimentary Report Now.
Generate Complete .NET Web Apps in Minutes . Download Iron Speed Designer today.



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES