gpt4 book ai didi

c - 未调用 sqlite3 C 用户定义函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:20:09 25 4
gpt4 key购买 nike

第一次发帖!该站点在解决大量以前的技术问题上提供了至关重要的帮助。感谢您的辛勤工作,集体发言。

现在来谈谈我的问题。

我想编写一个 C sqlite3 UDF(用户定义函数)。假设函数名称是“myFunc”。

我在 Raspberry PI 3B 上工作 - Raspbian 默认值(最新发行版)。

test_table 具有以下架构:

create table test_table (
a integer,
b integer
);

小程序(测试方法)打开数据库并安装函数。然后无限期地等待触发事件。

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <signal.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/stat.h>

static void myFuncBody(sqlite3_context *context, int argc, sqlite3_value **argv)
{
printf("myFunc fired!\n");
fflush(stdout);
}

int main(int argc, char** argv)
{
sqlite3 *db_handler;
char *errMsg;
int error;

error = sqlite3_open("test.db", &db_handler);
if (error)
{
printf("Error opening the DB.\n");
exit(-2);
}

error = sqlite3_create_function(
db_handler,
"myFunc",
0,
SQLITE_UTF8,
NULL,
myFuncBody,
NULL,
NULL
);
if (error != SQLITE_OK)
{
printf("Error creating the function.\n");
}

for (;;);

return 0;
}

然后我在 sqlite3 控制台上单独打开 test.db:

$ sqlite3 test.db

$ sqlite> select myFunc();
Error: no such function: myFunc

我认为 myFunc 应该是可见的,但事实并非如此。

我也可以创建一个触发器,但结果显然不会改变。

$ sqlite>  create trigger trigger1 after insert on test_table begin select myFunc(); end;

$ sqlite> insert into test_table values(-100, -150);
Error: no such function: myFunc

我的目标只是收到有关 test_table 插入的通知。

我的方法基本上有问题吗?

如有任何帮助,我们将不胜感激。

问候,莫比奥

最佳答案

这里有个误区:

新定义的 C 函数仅在添加它的句柄(在您的情况下为 db_handler)的上下文中定义。它不是数据库文件 test.db 的 future 部分。

所以如果你做一个

sqlite3_exec(db_handler, "select myFunc()", ...);

在调用 sqlite3_create_function() 之后,它应该会按预期工作。

关于c - 未调用 sqlite3 C 用户定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41999029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com