ODBC Overview

MSDN Documentation

What is ODBC?

Open Database Connectivity (ODBC) is a standard API for accessing database management systems (DBMS). It enables applications to communicate with a variety of DBMSs using a uniform set of functions.

Key Concepts

Architecture

The ODBC architecture consists of three layers:

  1. Application Layer – Your program uses the ODBC API.
  2. Driver Manager Layer – Handles driver loading, connection pooling, and thread safety.
  3. Driver Layer – Communicates directly with the DBMS.
ODBC Architecture Diagram
Figure 1 – ODBC Architecture Overview

Getting Started

Follow these steps to start using ODBC in a C/C++ application on Windows:

// Example: Simple ODBC connection and query (C++)
#include <windows.h>
#include <sql.h>
#include <sqlext.h>

int main() {
    SQLHENV hEnv;
    SQLHDBC hDbc;
    SQLHSTMT hStmt;
    SQLRETURN ret;

    // Allocate environment handle
    ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv);
    if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) return -1;

    // Set ODBC version
    SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);

    // Allocate connection handle
    SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc);

    // Connect using a DSN
    ret = SQLConnect(hDbc,
                     (SQLCHAR *)"MyDSN", SQL_NTS,
                     (SQLCHAR *)"username", SQL_NTS,
                     (SQLCHAR *)"password", SQL_NTS);
    if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
        // handle error
        return -1;
    }

    // Allocate statement handle
    SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt);

    // Execute a query
    ret = SQLExecDirect(hStmt, (SQLCHAR *)"SELECT TOP 10 * FROM Employees", SQL_NTS);
    if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO) {
        // Process results...
    }

    // Cleanup
    SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
    SQLDisconnect(hDbc);
    SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
    SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
    return 0;
}

Further Resources