> 文章列表 > C++写数据库乱码解决方案

C++写数据库乱码解决方案

C++写数据库乱码解决方案

c++在使用数据库的过程中,如果不在utf-8环境下编码,就会出现sql语句中包含中文,会报错;如果是从数据库表中查询数据,如果数据库表中的某些字段为中文,查询结果也不能正常显示,出现这种情况的原因是因为数据的编码与工程的编码不一致造成的。

数据库的编码默认为UTF-8编码,而vc++工程中所编写的SQL语句,可能是Unciode或者ASCII码,特别是ASCII码,如果不进行转换,写入数据库以及从数据库中读出的数,都会是乱码(只针对中文字符),因此,本文主要写一下各种编码下的编码转换:
void AscllToUtf8(char ascll[], char utf8[])
{
//先将ASCII码转换为Unicode编码
int nlen = MultiByteToWideChar(CP_ACP, 0, ascll, -1, NULL, NULL);
wchar_t* pUnicode = new wchar_t[20];
memset(pUnicode, 0, nlen * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, ascll, -1, (LPWSTR)pUnicode, nlen);
std::wstring wsUnicode = pUnicode;
//将Unicode编码转换为UTF-8编码
nlen = WideCharToMultiByte(CP_UTF8, 0, wsUnicode.c_str(), -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_UTF8, 0, wsUnicode.c_str(), -1, utf8, nlen, NULL, NULL);
}

//将UTF-8编码转换为ASCII编码
void Utf8ToASCII(char* utf8, char ascll[])
{
std::string str = utf8;
//先将UTF8编码转换为Unicode编码
int nLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
wchar_t* pwcUnicode = new wchar_t[nLen];
memset(pwcUnicode, 0, nLen * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, (LPWSTR)pwcUnicode, nLen);
//将Unicode编码转换为ASCII编码
nLen = WideCharToMultiByte(CP_ACP, 0, pwcUnicode, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, pwcUnicode, -1, ascll, nLen, NULL, NULL);
}

//将ASCII编码转换为Unicode编码
void AscllToUnicode(char ascll[], wchar_t unicode[])
{
int nlen = MultiByteToWideChar(CP_ACP, 0, ascll, -1, NULL, NULL);
MultiByteToWideChar(CP_ACP, 0, ascll, -1, (LPWSTR)unicode, nlen);
}

//将UTF-8编码转换为Unicode编码
void Utf8ToUnicode(char* utf8, wchar_t unicode[])
{
std:: string sUTF8 = utf8;
int nLen = MultiByteToWideChar(CP_UTF8, 0, sUTF8.c_str(), -1, NULL, 0);
MultiByteToWideChar(CP_UTF8, 0, sUTF8.c_str(), -1, (LPWSTR)unicode, nLen);
}

//将Unicode编码转换为ASCII编码
void UnicodeToUtf8(wchar_t unicode[], char ascll[])
{
int nLen = WideCharToMultiByte(CP_ACP, 0, unicode, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, unicode, -1, ascll, nLen, NULL, NULL);
}