加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将自定义sqlite函数添加到Qt应用程序

发布时间:2020-12-12 18:57:35 所属栏目:百科 来源:网络整理
导读:我正在尝试将自定义sqlite3 regexp函数添加到我的Qt应用程序中(按照 this answer的建议).但是当我调用sqlite3_create_function函数时,我收到消息该程序意外地完成了.当我调试时,它终止于sqlite3_mutex_enter中的分段错误.下面有一个MWE,对绝对文件路径道歉.
我正在尝试将自定义sqlite3 regexp函数添加到我的Qt应用程序中(按照 this answer的建议).但是当我调用sqlite3_create_function函数时,我收到消息该程序意外地完成了.当我调试时,它终止于sqlite3_mutex_enter中的分段错误.下面有一个MWE,对绝对文件路径道歉.

我的代码中的regexp实现是从this site开始的;它也与msign函数here失败.对driver() – > handle()的各种检查直接来自Qt文档.

顺便说一下,我使用select sqlite_version();确定Qt 5.5使用sqlite版本3.8.8.2.我通过查看Qt GitHub存储库中的旧提交找到了that version.

MWE.pro

QT       += core gui
TARGET = MWE
TEMPLATE = app
QT += sql
SOURCES += main.cpp 
    D:QtQt5.5.05.5Src3rdpartysqlitesqlite3.c

HEADERS  += D:QtQt5.5.05.5Src3rdpartysqlitesqlite3.h

main.cpp中

#include <QtSql>

#include "D:/Qt/Qt5.5.0/5.5/Src/3rdparty/sqlite/sqlite3.h"

void qtregexp(sqlite3_context* ctx,int argc,sqlite3_value** argv)
{
    QRegExp regex;
    QString str1((const char*)sqlite3_value_text(argv[0]));
    QString str2((const char*)sqlite3_value_text(argv[1]));

    regex.setPattern(str1);
    regex.setCaseSensitivity(Qt::CaseInsensitive);

    bool b = str2.contains(regex);

    if (b)
    {
        sqlite3_result_int(ctx,1);
    }
    else
    {
        sqlite3_result_int(ctx,0);
    }
}

int main(int argc,char *argv[])
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("my.db");
    db.open();

    QVariant v = db.driver()->handle();
    if (v.isValid() && qstrcmp(v.typeName(),"sqlite3*")==0) {
        sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());
        if (db_handle != 0) { // check that it is not NULL
            // This shows that the database handle is generally valid:
            qDebug() << sqlite3_db_filename(db_handle,"main");
            sqlite3_create_function(db_handle,"regexp",2,SQLITE_UTF8 | SQLITE_DETERMINISTIC,NULL,&qtregexp,NULL);
            qDebug() << "This won't be reached."

            QSqlQuery query;
            query.prepare("select regexp('p$','tap');");
            query.exec();
            query.next();
            qDebug() << query.value(0).toString();
        }
    }
    db.close();
}

解决方法

从Qt,according to this forum post获取数据库句柄后,需要调用sqlite3_initialize().

...
    sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());
    if (db_handle != 0) { // check that it is not NULL
        sqlite3_initialize();
    ...

这解决了这个问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读