VS2019 c++使用sqlite3中文乱码解决方案

sqlite3乱码,小白搜了一下午,终于,windows系统下(我是VS2019编辑器)默认c++默认编码为GB2312,而sqlite3的编码为UTF-8,取出来时自然乱码

操作

需执行SQL语句时将执行的SQL字符串转化为UTF-8编码
从数据库取出数据后再转化为GB2321,即可在C++中正确显示

#include 
//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互转,我裂开了

你可能感兴趣的:(问题解决,c++,sqlite3,数据库,乱码)