[问题] 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