ODBC (Open Database Connectivity)

Overview

The Open Database Connectivity (ODBC) API provides a standard interface for accessing relational databases from Windows applications. ODBC enables you to write a single set of code that can communicate with many different database management systems (DBMS) by using appropriate drivers.

Key Benefits

Supported Platforms

Microsoft Windows 10, Windows Server 2019 and later. 32‑bit and 64‑bit applications are supported via the appropriate ODBC driver.

Getting Started

  1. Install the required ODBC driver for your target DBMS (e.g., SQL Server, MySQL, PostgreSQL).
  2. Create a Data Source Name (DSN) using ODBC Data Sources in Control Panel or programmatically via the ODBC API.
  3. Include sql.h and sqlext.h in your C/C++ project.
  4. Link against odbc32.lib (or iodbc.lib on Linux).
  5. Use the Connection Functions (SQLDriverConnect, SQLConnect) to open a connection.

Minimal Example (C++)

#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <iostream>

int main() {
    SQLHANDLE env, dbc;
    SQLRETURN ret;

    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
    SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
    SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);

    ret = SQLDriverConnect(dbc, NULL,
        (SQLCHAR*)"Driver={SQL Server};Server=localhost;Database=AdventureWorks;Trusted_Connection=Yes;",
        SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);

    if (SQL_SUCCEEDED(ret)) {
        std::cout << "Connection succeeded." << std::endl;
        SQLDisconnect(dbc);
    } else {
        std::cerr << "Connection failed." << std::endl;
    }

    SQLFreeHandle(SQL_HANDLE_DBC, dbc);
    SQLFreeHandle(SQL_HANDLE_ENV, env);
    return 0;
}

Resources