原因:mysql一般默认是utf8字符,而在Windows上都是标准的GBK格式,所以会出现中文乱码:
解决:
#include "windows.h" //一定要添加这个头文件
std::string UtfToGbk(const char* utf8)
{
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
if (wstr) delete[] wstr;
return str;
}
用法:
cout << UtfToGbk(res->getString("name").c_str()) << endl;//其中res->getString("name")。这是使用connect c++调用的接口,name是数据库中的一列,并且是存储的中文形式。c_str()别忘了加
当然当你在Windows上执行mysql语句的时候可能有时候也需要用到中文查找,这个时候你就要把string转化成utf8了,不然数据到数据库那边也是乱码的,导致查找错误。下面是例子:
std::string string_To_UTF8(const std::string & str)
{
int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴
ZeroMemory(pwBuf, nwLen * 2 + 2);
::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);
int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
char * pBuf = new char[nLen + 1];
ZeroMemory(pBuf, nLen + 1);
::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
std::string retStr(pBuf);
delete[]pwBuf;
delete[]pBuf;
pwBuf = NULL;
pBuf = NULL;
return retStr;
}
//部分代码
string str = "张三";
std::string temp = string_To_UTF8(str);
res = stmt->executeQuery("select * from user where name='"+temp+"'");