Skip to main content

skip to main content

developerWorks  >  Java technology  >

Dynamic Web-based data access using JSP and JDBC technologies

developerWorks


Listing 2. JDBC code segment showing exception handling and resource cleanup

try
{
   Connection connection = DriverManager.getConnection(URL, user, password);

    try
    {
        Statement statement = connection.createStatement();
        logSQLWarnings(connection.getWarnings());
        connection.clearWarnings();

        try
        {
            ResultSet results = statement.executeQuery(sqlQuery);
            logSQLWarnings(statement.getWarnings());

            try
            {
                while (results.next())
                {
                    ... process query results ...
                    logSQLWarnings(results.getWarnings());
                }
            }
            catch (SQLException e)
            {
                logSQLExceptions(e);
            }
            finally
            {
                results.close();
            }
        }
        catch (SQLException e)
        {
            logSQLExceptions(e);
        }
        finally
        {
            statement.close();
        }
    }
    catch (SQLException e)
    {
        logSQLExceptions(e);
    }
    finally
    {
       connection.close();
    }
}
catch (SQLException e)
{
    logSQLExceptions(e);
}

Return to article