【在控制台中顯示UTF-8字符串的方法】
#include <iostream>
#include <mysql/mysql.h>
#include <Windows.h>
using namespace std;
#define DB_PASSWORD "密碼"
int main(void)
{
MYSQL conn;
mysql_init(&conn);
if (!mysql_real_connect(&conn, "127.0.0.1", "root", DB_PASSWORD, "super", NULL, NULL, NULL))
{
cout << "無法連接數據庫" << endl;
return 1;
}
mysql_set_character_set(&conn, "utf8");
char *sql = "SELECT * FROM role ORDER BY ID";
mysql_query(&conn, sql);
MYSQL_RES *rs = mysql_store_result(&conn);
MYSQL_ROW row;
int i;
for (i = 0; row = mysql_fetch_row(rs); i++)
{
// 將row[1]從UTF8轉換到UTF16,然後再轉換為ANSI
int n = MultiByteToWideChar(CP_UTF8, NULL, row[1], -1, NULL, NULL);
wchar_t *wstr = new wchar_t[n];
MultiByteToWideChar(CP_UTF8, NULL, row[1], -1, wstr, n);
n = WideCharToMultiByte(CP_ACP, NULL, wstr, -1, NULL, NULL, NULL, NULL);
char *str = new char[n];
WideCharToMultiByte(CP_ACP, NULL, wstr, -1, str, n, NULL, NULL);
cout << "第" << row[0] << "條記錄: ";
cout << str << endl;
delete[] str;
delete[] wstr;
}
mysql_free_result(rs);
mysql_close(&conn);
system("pause");
return 0;
}
【運行結果】