ODBC API Reference
The ODBC (Open Database Connectivity) API provides a set of functions, structures, and constants for interacting with relational databases in a uniform manner. This reference describes each element in detail.
Functions
Name | Header | Description |
---|---|---|
SQLAllocHandle | sql.h | Allocates an environment, connection, or statement handle. |
SQLFreeHandle | sql.h | Frees a handle allocated by SQLAllocHandle . |
SQLConnect | sql.h | Establishes a connection to a data source. |
SQLDisconnect | sql.h | Terminates a connection. |
SQLExecDirect | sql.h | Executes a SQL statement directly. |
SQLPrepare | sql.h | Prepares a SQL statement for execution. |
SQLExecute | sql.h | Executes a prepared statement. |
SQLFetch | sql.h | Retrieves the next row of data from a result set. |
Structures
Name | Header | Purpose |
---|---|---|
SQLLEN | sqltypes.h | Signed integer for lengths and offsets. |
SQLULEN | sqltypes.h | Unsigned integer for lengths and offsets. |
SQLINTEGER | sqltypes.h | Standard 32‑bit integer. |
SQLSMALLINT | sqltypes.h | Standard 16‑bit integer. |
Constants
#define SQL_SUCCESS 0 #define SQL_SUCCESS_WITH_INFO 1 #define SQL_ERROR -1 #define SQL_NO_DATA 100 #define SQL_NULL_DATA -1 #define SQL_NTS -3
These constants indicate the return status of ODBC functions.
Example: Connecting and Querying
#include <windows.h> #include <sql.h> #include <sqlext.h> int main() { SQLHANDLE env, dbc, stmt; SQLRETURN ret; // Allocate environment handle ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0); // Allocate connection handle SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc); // Connect to DSN ret = SQLConnect(dbc, (SQLCHAR*) "MyDSN", SQL_NTS, (SQLCHAR*) "username", SQL_NTS, (SQLCHAR*) "password", SQL_NTS); if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) { printf("Connection failed\n"); return 1; } // Allocate statement handle SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt); // Execute query ret = SQLExecDirect(stmt, (SQLCHAR*) "SELECT id, name FROM Employees", SQL_NTS); if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO) { SQLINTEGER id; SQLCHAR name[100]; while (SQLFetch(stmt) == SQL_SUCCESS) { SQLGetData(stmt, 1, SQL_C_SLONG, &id, 0, NULL); SQLGetData(stmt, 2, SQL_C_CHAR, name, sizeof(name), NULL); printf("ID: %d, Name: %s\n", id, name); } } // Clean up SQLFreeHandle(SQL_HANDLE_STMT, stmt); SQLDisconnect(dbc); SQLFreeHandle(SQL_HANDLE_DBC, dbc); SQLFreeHandle(SQL_HANDLE_ENV, env); return 0; }
This example demonstrates how to allocate handles, connect to a data source, execute a query, fetch results, and clean up resources.