[問題] VC++ 讀取MySQL資料顯示亂碼

作者: chingyue (ChingYue)   2017-04-17 16:44:27
開發平台(Platform): (Ex: Win10, Linux, ...)
Win7
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
VC++(Win32 API)
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
MySQL C API
問題(Question):
各位前輩大家好
小弟最近找到一個VC++使用MySQL C API讀取MySQL的範例
顯示英文數字時沒有問題
可是要顯示中文的結果都是亂碼
編碼格式也設定utf8了
請各位大哥大姊幫幫小弟除錯
執行結果:http://i.imgur.com/UA2vKvO.jpg
資料庫設定:http://i.imgur.com/c2vxNJz.jpg
資料表內容:http://i.imgur.com/u31gzWx.jpg
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <Windows.h>
#include <mysql.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
char user[] = "root";
char pswd[] = "";
char host[] = "localhost";
char table[] = "mms_gs";
unsigned int port = 3306;
MYSQL myCont;
MYSQL_RES *result;
MYSQL_ROW sql_row;
int res;
mysql_init(&myCont);
if (mysql_real_connect(&myCont, host, user, pswd, table, port, NULL, 0))
{
mysql_query(&myCont, "SET NAMES utf8"); //设置编码格式
res = mysql_query(&myCont, "select * from mms_reserved");//查询
if (!res)
{
result = mysql_store_result(&myCont);
if (result)
{
while (sql_row = mysql_fetch_row(result))//获取具体的数据
{
cout << "BOOKNAME:" << sql_row[1] << endl;
cout << " SIZE:" << sql_row[2] << endl;
}
}
}
else
{
cout << "query sql failed!" << endl;
}
}
else
{
cout << "connect failed!" << endl;
}
if (result != NULL)
mysql_free_result(result);
mysql_close(&myCont);
system("pause");
return 0;
}
補充說明(Supplement):
程式碼網址(codepad):http://codepad.org/WR138lCu
程式碼網址(codepile):https://www.codepile.net/pile/ny77n1yq
作者: johnpage (johnpage)   2017-04-17 18:24:00
Big5
作者: LPH66 (-6.2598534e+18f)   2017-04-17 22:16:00
應該說問題是在最後一步你把資料 cout 出來時編碼不對沒弄錯的話你到取資料為止都是對的, 但你取得的資料是 utf8但 cout 到 console 時因為 console 是 big5 就炸了
作者: MOONRAKER (㊣牛鶴鰻毛人)   2017-04-18 15:43:00
在Linux下跑,用utf8終端機開,就有utf8了
作者: johnpage (johnpage)   2017-04-18 16:02:00
執行 chcp 65001命令

Links booklink

Contact Us: admin [ a t ] ucptt.com