Example: Logging items from the SQL diagnostics area

In this example, an application needs to log all errors for security reasons. The log could be used to monitor the health of a system or to monitor for inappropriate use of a database.

For each SQL error that occurs, an entry is placed in the log. The entry includes when the error occurred, what user was using the application, what type of SQL statement was run, the returned SQLSTATE value, and the message number and corresponding complete message text.

char stmt_command[256];
long int error_count;
long int condition_number;
char auth_id[256];
char error_state[6];
char msgid[128];
char msgtext[1024];

EXEC SQL WHENEVER SQLERROR GOTO error;

(application code)


error:
EXEC SQL GET DIAGNOSTICS :stmt_command = COMMAND_FUNCTION,
                         :error_count = NUMBER;

for (condition_number=1;i<=error_count;++condition_number)
{
  EXEC SQL GET DIAGNOSTICS CONDITION :condition_number
    :auth_id = DB2_AUTHORIZATION_ID,
    :error_state = RETURNED_SQLSTATE,
    :msgid = DB2_MESSAGE_ID,
    :msgtext = DB2_MESSAGE_TEXT;

  EXEC SQL INSERT INTO error_log VALUES(CURRENT_TIMESTAMP,
    :stmt_command,
    :condition_number,
    :auth_id,
    :error_state,
    :msgid,
    :msgtext);
}
Related information
GET DIAGNOSTICS