Handling errors

Errors in ODBC are reported using the return value from each of the ODBC function calls and either the SQLGetDiagField function or the SQLGetDiagRec function. The SQLError function was used in ODBC versions up to, but not including, version 3. As of version 3, the SQLError function has been replaced by the SQLGetDiagRec and SQLGetDiagField functions.

Every ODBC function returns a SQLRETURN that is one of the following status codes:

Status code

Description

SQL_SUCCESS

No error.

SQL_SUCCESS_WITH_INFO

The function completed, but a call to SQLGetDiagRec will indicate a warning.

The most common cause for this status is that a value being returned is too long for the buffer provided by the application.

SQL_INVALID_HANDLE

An invalid environment, connection, or statement handle was passed as a parameter.

This often happens if a handle is used after it has been freed, or if the handle is the null pointer.

SQL_NO_DATA

There is no information available.

The most common use for this status is when fetching from a cursor; it indicates that there are no more rows in the cursor.

SQL_NEED_DATA

Data is needed for a parameter.

This is an advanced feature described in the ODBC Software Development Kit documentation under SQLParamData and SQLPutData.

Every environment, connection, and statement handle can have one or more errors or warnings associated with it. Each call to SQLGetDiagRec returns the information for one error and removes the information for that error. If you do not call SQLGetDiagRec to remove all errors, the errors are removed on the next function call that passes the same handle as a parameter.

Each call to SQLGetDiagRec can pass either an environment, connection, or statement handle. The first call passes in a handle of type SQL_HANDLE_DBC to get the error associated with a connection. The second call passes in a handle of type SQL_HANDLE_STMT to get the error associated with the statement that was just executed.

SQLGetDiagRec returns SQL_SUCCESS if there is an error to report (not SQL_ERROR), and SQL_NO_DATA_FOUND if there are no more errors to report.

Example 1

The following code fragment uses SQLGetDiagRec and return codes:

retcode = SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt );
if( retcode == SQL_ERROR )
{
   SQLGetDiagRec(SQL_HANDLE_DBC,dbc, 1, NULL,NULL,
     errmsg, 100, NULL);
   /* Assume that print_error is defined */  
   print_error( "Allocation failed", errmsg ); 
   return;
} 

Example 2

retcode = SQLExecDirect( stmt,
   "delete from sales_order_items where id=2015", 
   SQL_NTS ); 
if( retcode == SQL_ERROR ) 
{ 
   SQLGetDiagRec(SQL_HANDLE_STMT,stmt, 1, NULL,NULL,
     errmsg, 100, NULL);
   /* Assume that print_error is defined */ 
   print_error( "Failed to delete items", errmsg );       return; 
}