Handling SQL errors in an SQLJ application

SQLJ clauses use the JDBC class java.sql.SQLException for error handling.

Procedure

To handle SQL errors in SQLJ applications, following these steps:

  1. Import the java.sql.SQLException class.
  2. Use the Java™ error handling try/catch blocks to modify program flow when an SQL error occurs.
  3. Obtain error information from the SQLException.

    You can use the getErrorCode method to retrieve SQL error codes and the getSQLState method to retrieve SQLSTATEs.

    If you are using the IBM® Data Server Driver for JDBC and SQLJ, obtain additional information from the SQLException by casting it to a DB2Diagnosable object, in the same way that you obtain this information in a JDBC application.

Example

The following code prints out the SQL error that occurred if a SELECT statement fails.
try {
  #sql [ctxt] {SELECT LASTNAME INTO :empname
    FROM EMPLOYEE WHERE EMPNO='000010'};
}
catch(SQLException e) {
  System.out.println("Error code returned: " + e.getErrorCode());
}