我用如何在C++中将unicode字符串插入sqllite?
sqlite3_open16(v_st,&m_db)//SQLITE_OK
我想插入Unicode字符串。 例子:
sqlite3_exec(m_db,"UPDATE t1 SET a1='text'",0,0,0); //is good
但
sqlite3_exec(m_db,"UPDATE t1 SET a1='текст'",0,0,0); //is bad
我用如何在C++中将unicode字符串插入sqllite?
sqlite3_open16(v_st,&m_db)//SQLITE_OK
我想插入Unicode字符串。 例子:
sqlite3_exec(m_db,"UPDATE t1 SET a1='text'",0,0,0); //is good
但
sqlite3_exec(m_db,"UPDATE t1 SET a1='текст'",0,0,0); //is bad
当您使用sqlite3_open16
功能打开DB与UTF-16编码。 当您使用sqlite3_exec(m_db,"UPDATE t1 SET a1='текст'",0,0,0)
函数时,您使用编译器的编码(默认为UTF-8或cp1251)。
您应该在两种情况下使用相同的编码。您可以执行以下其中一项操作:
1)使用sqlite3_open
函数以UTF-8编码打开它,并确保您的编译器使用UTF-8;
或
2)将您的编译器编码更改为UTF-16;
或
3)使用SQL语句PRAGMA encoding = "UTF-8"
string ANSItoUTF16le(const char* v_str)
{
string t_res;
unsigned char* t_buf=(unsigned char*)v_str;
auto t_size=strlen(v_str);
unsigned char t_s='А',t_f='п',t_E='Ё',t_e='Ё',t2_s='р',t2_f='я';
unsigned char t_c;
for(auto i=0;i<t_size;i++)
{
if(t_buf[i]>=t_s&&t_buf[i]<=t_f)
{
t_res+='\xD0';
t_c='\x90'+t_buf[i]-t_s;
t_res+=t_c;
continue;
}
if(t_buf[i]>=t2_s&&t_buf[i]<=t2_f)
{
t_res+='\xD1';
t_c='\x80'+t_buf[i]-t2_s;
t_res+=t_c;
continue;
}
if(t_buf[i]==t_E)
{
t_res+="\xD0\x01";
continue;
}
if(t_buf[i]==t_e)
{
t_res+="\xD1\x91";
continue;
}
t_res+=v_str[i];
}
return t_res;
}
和
sqlite3_exec(m_db,ANSItoUTF16le("UPDATE t1 SET a1='текст'").c_str(),0,0,0);
谢谢安德烈! –
您可以通过使用sqlite3的顶部的包装类插入Unicode字符串到sqllite在C++中。
CppSqlite3U是一个围绕SQLite数据库的unicode包装。它允许使用UNICODE类型,如wchar_t(而不是char),或者可以从here下载。也在this article中描述。例如:由execQuery执行的查询可以是LPCTSTR类型,这意味着它可以是一个宽字符或字符的数组,取决于UNICODE是否在您的项目中定义。
CppSQLite3Query execQuery(LPCTSTR szSQL);
非常感谢! –