最近在读写mysql数据库时,碰到乱码的问题,研究一番发现vs项目下,默认编码Unicode,但我的数据库默认utf8,所以读取数据的时候中文乱码。最终通过以下方法解决:
1、写入数据库时设置编码为gbk
mysql_query(connect, "set names gbk")
2、读取数据库时设置编码为utf8
mysql_query(connect, "set names utf8")
3、读取时将utf8转为unicode
-
wchar_t* Utf8_2_Unicode(
char* row_i)
-
{
-
int len = MultiByteToWideChar(CP_UTF8,
0, row_i,
strlen(row_i),
NULL,
0);
-
wchar_t *wszStr =
new
wchar_t[len +
1];
-
MultiByteToWideChar(CP_UTF8,
0, row_i,
strlen(row_i), wszStr, len);
-
wszStr[len] =
'\0';
-
return wszStr;
-
}
结果对比:
数据库:
code:
-
#include "mysql/mysql.h"
-
#include <iostream>
-
#include <windows.h>
-
#include <tchar.h>
-
using
namespace
std;
-
-
wchar_t* Utf8_2_Unicode(
char* row_i)
-
{
-
int len = MultiByteToWideChar(CP_UTF8,
0, row_i,
strlen(row_i),
NULL,
0);
-
wchar_t *wszStr =
new
wchar_t[len +
1];
-
MultiByteToWideChar(CP_UTF8,
0, row_i,
strlen(row_i), wszStr, len);
-
wszStr[len] =
'\0';
-
return wszStr;
-
}
-
-
int main()
-
{
-
//初始化MYSQL
-
MYSQL *connect = mysql_init((MYSQL*)
0);;
-
-
//连接到MYSQL
-
connect = mysql_real_connect(connect,
"localhost",
"root",
"123",
"test",
3306,
NULL,
0);
-
if (connect ==
NULL)
-
{
-
return mysql_errno(connect);
-
}
-
-
//将编码设置为gbk
-
if (mysql_query(connect,
"set names gbk"))
-
{
-
return mysql_errno(connect);
-
}
-
-
//写入中文数据
-
if (mysql_query(connect,
"INSERT INTO country(序号,中文,英文) VALUES('3','美国','America')"))
-
{
-
return mysql_errno(connect);
-
}
-
-
//设置编码格式utf8
-
int ret = mysql_query(connect,
"set names utf8");
-
-
//读取中文数据
-
ret = mysql_query(connect,
"SELECT * FROM country");
-
if (ret)
-
{
-
return mysql_errno(connect);
-
}
-
else
-
{
-
//获取结果集
-
MYSQL_RES *res = mysql_store_result(connect);
-
MYSQL_ROW row;
-
while (row = mysql_fetch_row(res))
-
{
-
//将字符由utf8专转为unicode
-
wchar_t* m1 = Utf8_2_Unicode(row[
2]);
-
wchar_t* m2 = Utf8_2_Unicode(row[
1]);
-
MessageBox(
NULL, m1, m2,
NULL);
-
}
-
mysql_free_result(res);
-
}
-
mysql_close(connect);
-
getchar();
-
return
0;
-
}
转载:https://blog.csdn.net/lihaidong1991/article/details/104523599
查看评论