Open Database Connectivity (ODBC)
What is Open Database Connectivity (ODBC)?
Open Database Connectivity (ODBC) is a widely used data access technology that enables applications written in different programming languages to access data stored in different database management systems (DBMS). It consists of a set of standards and APIs that provide a way for applications to connect to databases and execute SQL statements.
ODBC provides a standardized way for applications to access data stored in different databases, regardless of the database vendor or type. To use ODBC, you must first install an ODBC driver for the database you want to connect to. Then, you can use the ODBC API to create a connection to the database, send SQL statements, and process the results.
One advantage of ODBC is that it is platform-independent, which means that the same ODBC code can be used on different operating systems, as long as an ODBC driver is available for that system. ODBC is widely supported and is commonly used to connect to databases from applications written in languages such as C, C++, and Python.
Here's a simple example of how to use ODBC to connect to a database and execute a SELECT statement in C:
- include <stdio.h>
- include <sql.h>
- include <sqlext.h>
int main() {
SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret; /* ODBC API return status */
/* Allocate an environment handle */ SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); /* Set the ODBC version environment attribute */ SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0); /* Allocate a connection handle */ SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
/* Connect to the database */ SQLDriverConnect(dbc, NULL, "DSN=test;UID=username;PWD=password", SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);
/* Allocate a statement handle */ SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
/* Execute a SELECT statement */ SQLPrepare(stmt, "SELECT id, first, last, age FROM Employees", SQL_NTS); SQLExecute(stmt);
/* Bind columns in the result set to variables */ int id, age; char first[255], last[255]; SQLBindCol(stmt, 1, SQL_C_ULONG, &id, 0, NULL); SQLBindCol(stmt, 2, SQL_C_CHAR, first, 255, NULL); SQLBindCol(stmt, 3, SQL_C_CHAR, last, 255, NULL); SQLBindCol(stmt, 4, SQL_C_ULONG, &age, 0, NULL);
/* Fetch and print the results */ while((ret = SQLFetch(stmt)) == SQL_SUCCESS) { printf("ID: %d, Age: %d, First: %s, Last: %s\n", id, age, first, last); }
/* Clean up */ SQLFreeHandle(SQL_HANDLE_ST
See Also