VS2019 c++使用sqlite3中文亂碼解決方案

sqlite3亂碼,小白搜了一下午,終於,windows系統下(我是VS2019編輯器)默認c++默認編碼爲GB2312,而sqlite3的編碼爲UTF-8,取出來時自然亂碼

操作

需執行SQL語句時將執行的SQL字符串轉化爲UTF-8編碼
從數據庫取出數據後再轉化爲GB2321,即可在C++中正確顯示

#include <atlstr.h>
//UTF-8到GB2312的轉換
char* U2G(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;
}

//GB2312到UTF-8的轉換
char* G2U(const char* gb2312)
{
   
   
	int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
	len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
	if (wstr) delete[] wstr;
	return str;
}
int main()
{
   
   
	sqlite3 * db;
	sqlite3_open("a.db", &db);
	sqlite3_exec(db, G2U("insert into test values('阿巴','阿巴');"),NULL,NULL,NULL);//此處SQL語句轉化爲UTF-8
	sqlite3_stmt* stmt = NULL;
	if (sqlite3_prepare_v2(db, "select * from test", -1, &stmt, NULL) == SQLITE_OK)
	{
   
   
		while (sqlite3_step(stmt) == SQLITE_ROW)
		{
   
   
			char*a=(char*)sqlite3_column_text(stmt, 0);//取出的數據
			char*b = U2G(a);//將取出的數據轉化爲GB2312
			cout << b<< endl;//完美!
		}
	} 
	sqlite3_close(db);
}

煩死我了,這問題煩了我一下午,都說Unicode和UTF-8互轉,我裂開了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章