向Qt应用程序添加自定义sqlite函数
我正在尝试按照的建议将一个自定义sqlite3 regexp函数添加到我的Qt应用程序中。但是,只要我调用sqlite3_create_函数,我就会得到程序意外完成的消息。当我调试时,它在sqlite3\u mutex\u enter中的分段错误中终止。下面是一个MWE,对绝对文件路径表示歉意 我的代码中的regexp实现来自;msign函数也会失败。驱动程序->手柄的各种检查直接来自Qt文档 顺便说一句,我使用select sqlite_版本;确定Qt5.5使用sqlite版本3.8.8.2。我通过查看QtGithub存储库中的旧提交找到了 MWE.pro向Qt应用程序添加自定义sqlite函数,qt,sqlite,Qt,Sqlite,我正在尝试按照的建议将一个自定义sqlite3 regexp函数添加到我的Qt应用程序中。但是,只要我调用sqlite3_create_函数,我就会得到程序意外完成的消息。当我调试时,它在sqlite3\u mutex\u enter中的分段错误中终止。下面是一个MWE,对绝对文件路径表示歉意 我的代码中的regexp实现来自;msign函数也会失败。驱动程序->手柄的各种检查直接来自Qt文档 顺便说一句,我使用select sqlite_版本;确定Qt5.5使用sqlite版本3.8.8.2。
QT += core gui
TARGET = MWE
TEMPLATE = app
QT += sql
SOURCES += main.cpp \
D:\Qt\Qt5.5.0\5.5\Src\3rdparty\sqlite\sqlite3.c
HEADERS += D:\Qt\Qt5.5.0\5.5\Src\3rdparty\sqlite\sqlite3.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, 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获取数据库句柄后,需要调用sqlite3\u initialize
这就解决了问题
...
sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());
if (db_handle != 0) { // check that it is not NULL
sqlite3_initialize();
...