【在控制台中显示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;
}
【运行结果】