向Sqlite中写中文时候,sqlite是用的UTF-8编码的,所以要转码
// 获取到的中文数据的转码 void UTF8Transcoding(string &str)
{
int len = WideCharToMultiByte(CP_UTF8,0,CA2W((char*)str.data()),-1,NULL,0,NULL,NULL);
char *strNew = new char[len+1];
WideCharToMultiByte(CP_UTF8,0,CA2W((char*)str.data()),-1,strNew,len,NULL,NULL);
strNew[len] = '\0';
str.clear();
str = strNew;
delete[] strNew;
return ;
}
// 获取到的中文数据的转码
void Change(string &str)
{
int len = MultiByteToWideChar(CP_UTF8,0,str.data(),-1,NULL,0);
WCHAR *strNew = new WCHAR[len+1];
MultiByteToWideChar(CP_UTF8,0,str.data(),-1,strNew,len);
str.clear();
str = CW2A(strNew);
delete[] strNew;
return ;
}
一段例子
#include "stdafx.h"
#include
#include "atlbase.h"
#include
#include "sqlite3.h"
using namespace std;
void UTF8Transcoding(string &str)
{
int len = WideCharToMultiByte(CP_UTF8, 0, CA2W((char*)str.data()), -1, NULL, 0, NULL, NULL);
char *strNew = new char[len + 1];
WideCharToMultiByte(CP_UTF8, 0, CA2W((char*)str.data()), -1, strNew, len, NULL, NULL);
strNew[len] = '\0';
str.clear();
str = strNew;
delete[] strNew;
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *errMsg;
int rc;
sqlite3 *db;
rc = sqlite3_open("033001.db", &db);
auto sql = _T("create table if not exists user(ID varchar(20),Name varchar(20),Age int,Nation varchar(20),Major varchar(20));");
if (rc == SQLITE_OK)
{
//MessageBox(NULL, _T("打开数据库成功!"), _T("消息"), MB_OK | MB_ICONWARNING);
rc = sqlite3_exec(db, CW2A(sql, CP_UTF8), 0, 0, &errMsg);
if (rc != SQLITE_OK)
{
printf("创建表失败,错误码:%d,错误原因:%sn", rc, errMsg);
MessageBox(NULL, _T("创建表user失败!"), _T("错误"), MB_ICONWARNING);
}
for (int i = 1; i < 6; i++)
{
char c2[20] = "";
c2[0] = i + '0';
char c1[128] = "insert into user values('01','张三',";
char c3[128] = ",'汉','软件');";
strcat(c1, c2);
strcat(c1, c3);
string temp = c1;
UTF8Transcoding(temp);
const char* temp_c = temp.data();;
rc = sqlite3_exec(db, temp_c, 0, 0, &errMsg);
if (rc != SQLITE_OK)
{
printf("插入数据失败,错误码:%d,错误原因:%sn", rc, errMsg);
MessageBox(NULL, _T("插入数据失败!"), _T("错误"), MB_ICONWARNING);
}
}
}
return 0;
}