理论是:sqlite使用的是utf-8,c 中用的字符串是ascii或unicode编码。
所以使用时候要进行转化。插入中文时候要转化为utf-8,读取时候再转化回来。
//utf-8转unicode std::wstring utf82unicode(const std::string& utf8string) { int widesize = ::multibytetowidechar(cp_utf8, 0, utf8string.c_str(), -1, null, 0); if (widesize == error_no_unicode_translation) { throw std::exception("invalid utf-8 sequence."); } if (widesize == 0) { throw std::exception("error in conversion."); } std::vectorresultstring(widesize); int convresult = ::multibytetowidechar(cp_utf8, 0, utf8string.c_str(), -1, &resultstring[0], widesize); if (convresult != widesize) { throw std::exception("la falla!"); } return std::wstring(&resultstring[0]); } //unicode 转为 ascii std::string widebyte2acsi(std::wstring& wstrcode){ int asciisize = ::widechartomultibyte(cp_oemcp, 0, wstrcode.c_str(), -1, null, 0, null, null); if (asciisize == error_no_unicode_translation) { throw std::exception("invalid utf-8 sequence."); } if (asciisize == 0) { throw std::exception("error in conversion."); } std::vector resultstring(asciisize); int convresult = ::widechartomultibyte(cp_oemcp, 0, wstrcode.c_str(), -1, &resultstring[0], asciisize, null, null); if (convresult != asciisize) { throw std::exception("la falla!"); } return std::string(&resultstring[0]); } //utf-8 转 ascii std::string utf_82ascii(std::string& strutf8code){ using namespace std; string strret = ""; //先把 utf8 转为 unicode wstring wstr = utf82unicode(strutf8code); //最后把 unicode 转为 ascii strret = widebyte2acsi(wstr); return strret; } //ascii 转 unicode std::wstring acsi2widebyte(std::string& strascii){ using namespace std; int widesize = multibytetowidechar(cp_acp, 0, (char*)strascii.c_str(), -1, null, 0); if (widesize == error_no_unicode_translation) { throw std::exception("invalid utf-8 sequence."); } if (widesize == 0) { throw std::exception("error in conversion."); } std::vector resultstring(widesize); int convresult = multibytetowidechar(cp_acp, 0, (char*)strascii.c_str(), -1, &resultstring[0], widesize); if (convresult != widesize) { throw std::exception("la falla!"); } return std::wstring(&resultstring[0]); } //unicode 转 utf8 std::string unicode2utf8(const std::wstring& widestring){ using namespace std; int utf8size = ::widechartomultibyte(cp_utf8, 0, widestring.c_str(), -1, null, 0, null, null); if (utf8size == 0) { throw std::exception("error in conversion."); } std::vector resultstring(utf8size); int convresult = ::widechartomultibyte(cp_utf8, 0, widestring.c_str(), -1, &resultstring[0], utf8size, null, null); if (convresult != utf8size) { throw std::exception("la falla!"); } return std::string(&resultstring[0]); } //ascii 转 utf8 std::string ascii2utf_8(std::string& strasciicode) { using namespace std; string strret(""); //先把 ascii 转为 unicode wstring wstr = acsi2widebyte(strasciicode); //最后把 unicode 转为 utf8 strret = unicode2utf8(wstr); return strret; }
使用效果立竿见影:
可以看出,之前存进数据库的是乱码
改变之后已经成功将汉字存进去了