开发者

SQLite and UTF8

开发者 https://www.devze.com 2023-03-18 13:11 出处:网络
I have a strange problem. Cant add function to sqlite/ Write on c++/Qt. Function should do upper to Utf-8 simbols;

I have a strange problem. Cant add function to sqlite/ Write on c++/Qt. Function should do upper to Utf-8 simbols;

    this->db = QSqlDatabase::addDatabas开发者_高级运维e("QSQLITE");
    this->db.setDatabaseName(db);
    this->db.open();
    QVariant v = this->db.driver()->handle();
    sqlite3 *handler = *static_cast<sqlite3 **>(v.data());
    sqlite3_create_function( handler, "myUpper", 1, SQLITE_ANY, NULL, myFunc, NULL, NULL )

and the function is:

void myFunc( sqlite3_context * ctx, int argc, sqlite3_value ** argv )
{
        if( argc != 1 ) return;
        QString str;
        switch(sqlite3_value_type(argv[0]))
        {
                case SQLITE_NULL:
                {
                        sqlite3_result_text( ctx, "NULL", 4, SQLITE_STATIC );
                        break;
                }
                case SQLITE_TEXT:
                {
                        QString wstr((char*)sqlite3_value_text16(argv[0]));
                        wstr = wstr.toUpper();
                        sqlite3_result_text16( ctx, wstr.toStdString().c_str(), wstr.size() , SQLITE_TRANSIENT );
                        break;
                }
                default:
                        sqlite3_result_text( ctx, "NULL", 4, SQLITE_STATIC );
                break;
        }
}


You didn't specify the problem, but I suppose you should pass a pointer to the function:

sqlite3_create_function(handler, "myUpper", 1, SQLITE_ANY, NULL, &myFunc, NULL, NULL)

EDIT: I you're passing to the function wstr.toStdString().c_str(). This is not allowed because the pointer returned is only temporary and will go out of scope. What I would do is:

...
case SQLITE_TEXT: {
   QString wstr((char*)sqlite3_value_text(argv[0]));
   wstr = wstr.toUpper();
   QByteArray array = wstr.toLocal8Bit();
   const char* cstr = array.data();
   sqlite3_result_text(ctx, cstr, wstr.size() , SQLITE_TRANSIENT);
   break;
}
...

I didn't try it so check this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号