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);
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pailugou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值