ODBC(Open Database Connectivity)是一種用來對(duì)各種數(shù)據(jù)庫進(jìn)行訪問的開放式API。C語言提供了ODBC API,利用這個(gè)API可以使用各種編程語言對(duì)數(shù)據(jù)庫進(jìn)行操作。
MySQL是一個(gè)流行的開源關(guān)系型數(shù)據(jù)庫管理系統(tǒng)。C語言可以通過ODBC API訪問和操作MySQL數(shù)據(jù)庫。
#include#include #include #include int main() { SQLHENV env; // Environment handle SQLHDBC dbc; // Connection handle SQLHSTMT stmt; // Statement handle SQLRETURN ret; // Return code // Allocate environment handle ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); // Set ODBC version to 3 ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_UINTEGER); // Allocate connection handle ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc); // Connect to a database ret = SQLConnect(dbc, "MYSQLTESTDSN", SQL_NTS, "root", SQL_NTS, "password", SQL_NTS); if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) { // Error handling } // Allocate statement handle ret = SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt); // Execute SQL statement ret = SQLExecDirect(stmt, "SELECT * FROM users", SQL_NTS); // Bind columns in result set to variables int id; char name[255]; while (ret == SQL_SUCCESS) { ret = SQLFetch(stmt); if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO) { SQLGetData(stmt, 1, SQL_C_SLONG, &id, sizeof(id), NULL); SQLGetData(stmt, 2, SQL_C_CHAR, name, sizeof(name), NULL); printf("%d %s\n", id, name); } } // Free statement handle ret = SQLFreeHandle(SQL_HANDLE_STMT, stmt); // Disconnect from database ret = SQLDisconnect(dbc); // Free connection handle ret = SQLFreeHandle(SQL_HANDLE_DBC, dbc); // Free environment handle ret = SQLFreeHandle(SQL_HANDLE_ENV, env); return 0; }
以上的代碼演示了如何使用ODBC API來連接并讀取MySQL數(shù)據(jù)庫中的數(shù)據(jù)。