在C語言中,要連接MySQL數(shù)據(jù)庫可以使用ODBC(Open Database Connectivity)技術(shù)。ODBC是一種將應(yīng)用程序與數(shù)據(jù)存儲在不同廠商的數(shù)據(jù)庫中進行交互的標準。以下是使用ODBC庫在C語言中連接MySQL服務(wù)器的示例代碼:
#include#include #include #define SQL_RESULT_LEN 240 #define SQL_RETURN_CODE_LEN 1000 int main() { SQLHANDLE sqlenvhandle; SQLHANDLE sqlconnectionhandle; SQLHANDLE sqlstatementhandle; SQLRETURN retcode; char sqlquery[SQL_RETURN_CODE_LEN] = "SELECT * FROM table_name"; SQLCHAR retconstring[SQL_RETURN_CODE_LEN]; SQLCHAR sqlversion[] = "SQL Server Native Client 11.0"; retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { printf("Error allocating environment handle\n"); return 0; } retcode = SQLSetEnvAttr(sqlenvhandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { printf("Error setting environment attribute\n"); return 0; } retcode = SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { printf("Error allocating connection handle\n"); return 0; } //連接參數(shù) SQLCHAR connection_string[] = "DRIVER={MySQL ODBC 5.3 Driver};SERVER=localhost;DATABASE=test;UID=root;PWD=123456;"; retcode = SQLDriverConnect(sqlconnectionhandle, NULL, (SQLCHAR*)connection_string, SQL_NTS, retconstring, SQL_RETURN_CODE_LEN, NULL, SQL_DRIVER_COMPLETE); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { printf("Error connecting to database\n"); return 0; } retcode = SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { printf("Error allocating statement handle\n"); return 0; } retcode = SQLExecDirect(sqlstatementhandle, (SQLCHAR*)sqlquery, SQL_NTS); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { printf("Error executing query\n"); return 0; } SQLCHAR name[SQL_RESULT_LEN]; while (SQLFetch(sqlstatementhandle) == SQL_SUCCESS) { SQLGetData(sqlstatementhandle, 1, SQL_C_CHAR, name, SQL_RESULT_LEN, NULL); printf("%s", name); } SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle); SQLDisconnect(sqlconnectionhandle); SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle); SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle); return 0; }
在上述代碼中,首先通過SQLAllocHandle函數(shù)分配環(huán)境句柄、連接句柄和語句句柄。然后通過SQLSetEnvAttr函數(shù)設(shè)置ODBC版本。接著通過SQLDriverConnect函數(shù)連接數(shù)據(jù)庫,并將連接字符串傳遞給函數(shù)。最后通過SQLExecDirect函數(shù)執(zhí)行查詢,并通過SQLFetch和SQLGetData函數(shù)獲取查詢結(jié)果。