如何在c ++中将unicode字符串插入sqlite?

时间:2014-01-25 11:25:34

标签: sqlite unicode

我用过

 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

3 个答案:

答案 0 :(得分:1)

使用sqlite3_open16功能时,使用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"

答案 1 :(得分:1)

    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);

答案 2 :(得分:0)

您可以使用sqlite3上的包装类在c ++中将unicode字符串插入sqllite。

CppSqlite3U是SQLite数据库的unicode包装器。它允许使用UNICODE类型,例如wchar_t(而不是char),或者可以从here下载。也在this article中描述。例如:execQuery执行的查询可以是LPCTSTR类型,这意味着它可以是宽字符或字符数组,具体取决于项目中是否定义了UNICODE。

CppSQLite3Query execQuery(LPCTSTR szSQL); 
相关问题