JDBC Tutorial - JDBC Exceptions Handling








A SQL exception can occur in the driver or from the database.

For example, a syntax error in the SQL statement will result in a SQL exception. Or we do not have permission to update a table.

When such an exception occurs, an object of type SQLException will be passed to the catch clause.

The SQLException object has the following methods :

Method Description
getErrorCode( ) Gets the error number.
getMessage( ) Gets error message.
getSQLState( ) Gets the SQLstate string. For a database error, the five-digit XOPEN SQLstate code is returned.
getNextException( ) Gets the next Exception object in the exception chain.
printStackTrace( ) Prints the current exception and its backtrace to a standard error stream.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream specified.
printStackTrace(PrintWriter w) Prints this throwable and its backtrace to the print writer specified.




Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// w w  w  .ja v  a  2  s  . com
public class Main {
  // JDBC driver name and database URL
  static final String JDBC_DRIVER = "org.hsqldb.jdbcDriver";
  static final String DB_URL = "jdbc:hsqldb:mem:db_file";

  // Database credentials
  static final String USER = "sa";
  static final String PASS = "";

  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    try {
      // STEP 2: Register JDBC driver
      Class.forName(JDBC_DRIVER);

      // STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);

      // STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      stmt.executeUpdate("CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256),  last VARCHAR(256),age INTEGER)");
      stmt.executeUpdate("INSERT INTO Employees VALUES(1,'Jack','Smith', 100)");

      ResultSet rs = stmt.executeQuery(sql);

      // STEP 5: Extract data from result set
      while (rs.next()) {
        // Retrieve by column name
        int id = rs.getInt("id");
        int age = rs.getInt("age");
        String first = rs.getString("first");
        String last = rs.getString("last");

        System.out.print("ID: " + id);
        System.out.print(", Age: " + age);
        System.out.print(", First: " + first);
        System.out.println(", Last: " + last);
      }
      // STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
    } catch (SQLException se) {
      se.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // finally block used to close resources
      try {
        if (stmt != null)
          stmt.close();
      } catch (SQLException se2) {
      }
      try {
        if (conn != null)
          conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      }
    }
    System.out.println("Goodbye!");
  }
}