Documentation

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

NameHeaderDescription
SQLAllocHandlesql.hAllocates an environment, connection, or statement handle.
SQLFreeHandlesql.hFrees a handle allocated by SQLAllocHandle.
SQLConnectsql.hEstablishes a connection to a data source.
SQLDisconnectsql.hTerminates a connection.
SQLExecDirectsql.hExecutes a SQL statement directly.
SQLPreparesql.hPrepares a SQL statement for execution.
SQLExecutesql.hExecutes a prepared statement.
SQLFetchsql.hRetrieves the next row of data from a result set.

Structures

NameHeaderPurpose
SQLLENsqltypes.hSigned integer for lengths and offsets.
SQLULENsqltypes.hUnsigned integer for lengths and offsets.
SQLINTEGERsqltypes.hStandard 32‑bit integer.
SQLSMALLINTsqltypes.hStandard 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.