How to: Process ODBC Errors (ODBC)

New: 14 April 2006

Two ODBC function calls can be used to retrieve ODBC messages: SQLGetDiagRec and SQLGetDiagField. To obtain primary ODBC-related information in the SQLState, pfNative, and ErrorMessage diagnostic fields, call SQLGetDiagRec until it returns SQL_NO_DATA. For each diagnostic record, SQLGetDiagField can be called to retrieve individual fields. All driver-specific fields must be retrieved using SQLGetDiagField.

SQLGetDiagRec and SQLGetDiagField are processed by ODBC Driver Manager, not an individual driver. ODBC Driver Manager does not cache driver-specific diagnostic fields until a successful connection has been made. Calling SQLGetDiagField for driver-specific diagnostic fields is not possible before a successful connection. This includes the ODBC connection commands, even if they return SQL_SUCCESS_WITH_INFO. Driver-specific diagnostic fields will not be available until the next ODBC function call.

Remarks

A complete sample is available that shows a simple error handler that calls SQLGetDiagRec for the standard ODBC information. It then tests for a valid connection, and if one exists, it calls SQLGetDiagField for the SQL Server ODBC driver-specific diagnostic fields.

The complete sample code is in the file, ProcessODBCErrors.cpp, which you can download from the SQL Server Downloads page on MSDN. This sample was developed using Microsoft Visual C++ 2005 and was developed for ODBC version 3.0 or later.

ms403305.security(en-US,SQL.90).gifSecurity Note:
When possible, use Windows Authentication. If Windows Authentication is not available, prompt users to enter their credentials at run time. Avoid storing credentials in a file. If you must persist credentials, you should encrypt them with the Win32 crypto API.

See Also

Other Resources

ODBC How-to Topics

Help and Information

Getting SQL Server 2005 Assistance