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
- Database‑agnostic code
- Rich API for SQL execution, transaction management, and metadata retrieval
- Native support in Win32, .NET, and Windows Store apps
- Extensible driver architecture
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
- Install the required ODBC driver for your target DBMS (e.g., SQL Server, MySQL, PostgreSQL).
- Create a Data Source Name (DSN) using
ODBC Data Sources
in Control Panel or programmatically via the ODBC API. - Include
sql.h
andsqlext.h
in your C/C++ project. - Link against
odbc32.lib
(oriodbc.lib
on Linux). - 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;
}