在使用C語言操作MySQL數(shù)據(jù)庫時,可能會遇到UTF8編碼下不能存儲特殊字符的問題,這時候可以使用UTF8MB4編碼,來解決該問題。
//連接MySQL數(shù)據(jù)庫 MYSQL mysql; mysql_init(&mysql); mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8mb4"); MYSQL *conn = mysql_real_connect(&mysql, host, user, password, database, port, NULL, CLIENT_MULTI_RESULTS | CLIENT_MULTI_STATEMENTS); //創(chuàng)建數(shù)據(jù)庫表時指定使用UTF8MB4編碼 const char* sql = "CREATE TABLE test(id int, name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci)"; mysql_real_query(conn, sql, strlen(sql)); //插入數(shù)據(jù)時使用mbstowcs函數(shù)將其轉(zhuǎn)化為寬字符形式,避免亂碼 char *name = "特殊字符"; wchar_t wname[255]; mbstowcs(wname, name, strlen(name) + 1); MYSQL_STMT *stmt = mysql_stmt_init(conn); const char* sql2 = "INSERT INTO test (id, name) VALUES (?, ?)"; mysql_stmt_prepare(stmt, sql2, strlen(sql2)); MYSQL_BIND bind[2] = {0}; int id = 1; bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &id; bind[1].buffer_type = MYSQL_TYPE_STRING; bind[1].buffer = wname; bind[1].buffer_length = wcslen(wname)*sizeof(wchar_t); mysql_stmt_bind_param(stmt, bind); mysql_stmt_execute(stmt); mysql_stmt_close(stmt);
以上代碼演示了使用UTF8MB4編碼來解決特殊字符存儲問題的基本操作,值得注意的是,在使用UTF8MB4編碼時需要保證數(shù)據(jù)庫、表以及字符集都是該編碼,否則仍然會出現(xiàn)亂碼問題。