2. Embedded SQL for C : The SQL Communications Area : Error Handling Using the SQLCA : Explicit Error Handling
 
Share this page                  
Explicit Error Handling
Programs can also handle errors by inspecting values in the SQLCA structure at various points. For further details, see the SQL Reference Guide.
The following example is functionally the same as the previous example, except that the error handling is hard-coded in C statements.
Example: Explicit error handling
exec sql include sqlca;
# define NOT_FOUND 100
Db_Test()
{
    exec sql begin declare section;
        short eno;
        char ename[21];
        char age;
    exec sql end declare section;
    exec sql declare empcsr cursor for
        select eno, ename, age
        from employee;
    /* Exit if database cannot be opened */
    exec sql connect personnel;
    if (sqlca.sqlcode < 0)
    {
        printf("Cannot access database.\n");
        exit(-1);
    }
/* Error if cannot open cursor */
exec sql open empcsr;
 if (sqlca.sqlcode < 0)
    Clean_Up("OPEN \"empcsr\"");
printf("Some values from the \"employee\"
    table.\n");
/*
** The last executable embedded SQL statement was an OPEN, so we know
** that the value of "sqlcode" cannot be SQLERROR or NOT FOUND.
*/
while (sqlca.sqlcode == 0)
/* Loop broken by NOT FOUND */
{
        exec sql fetch empcsr
            into :eno, :ename, :age;
        if (sqlca.sqlcode < 0)
             Clean_Up("FETCH <"empcsr\"");
        /* Do not print the last values twice */
        else if (sqlca.sqlcode != NOT_FOUND)
        printf("%d, %s, %d\n", eno, ename, age);
    }
    exec sql close empcsr;
    exec sql disconnect;
}
/*
** Clean_Up: Error handling procedure
*/
Clean_Up(stmt)
 char *stmt;
 {
    exec sql begin declare section;
        char *err_stmt = stmt;
        char errmsg[101];
    exec sql end declare section;
    exec sql inquire_sql (:errmsg = ERRORTEXT);
    printf("Aborting because of error in %s:\n%s\n",
        err_stmt, errmsg);
    exec sql disconnect;
    exit(-1); /* Do not return to Db_Test */
}