如何在 SQLite 中创建用户定义的函数? [英] How can I create a user-defined function in SQLite?

查看:49
本文介绍了如何在 SQLite 中创建用户定义的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 android 中开发一个应用程序,我需要在 sqlite 中创建一个 udf.是否可以在 sqlite 中创建它?如果是,该怎么做?

I am developing an application in android and I need to create an udf in sqlite. Is it possible to create it in sqlite? And if yes how to do this?

推荐答案

SQLite 不像 Oracle 或 MS SQL Server 那样支持用户定义的函数.对于 SQLite,您必须在 C/C++ 中创建一个回调函数并使用 sqlite3_create_function 打电话.

SQLite does not have support for user-defined functions in the way that Oracle or MS SQL Server does. For SQLite, you must create a callback function in C/C++ and hook the function up using the sqlite3_create_function call.

遗憾的是,Android 的 SQLite API 不允许直接通过 Java 调用 sqlite3_create_function.为了让它工作,你需要编译 SQLite C 库NDK.

Unfortunately, the SQLite API for Android does not allow for the sqlite3_create_function call directly through Java. In order to get it to work you will need to compile the SQLite C library with the NDK.

如果您仍然感兴趣,请阅读 2.3 用户定义函数...

And if you are still interested read 2.3 User-defined functions...

这里是如何创建一个函数来查找字符串的第一个字节.

Here's how to create a function that finds the first byte of a string.

static void firstchar(sqlite3_context *context, int argc, sqlite3_value **argv)
{
    if (argc == 1) {
        char *text = sqlite3_value_text(argv[0]);
        if (text && text[0]) {
          char result[2]; 
          result[0] = text[0]; result[1] = '';
          sqlite3_result_text(context, result, -1, SQLITE_TRANSIENT);
          return;
        }
    }
    sqlite3_result_null(context);
}

然后将函数附加到数据库中.

Then attach the function to the database.

sqlite3_create_function(db, "firstchar", 1, SQLITE_UTF8, NULL, &firstchar, NULL, NULL)

最后,在sql语句中使用该函数.

Finally, use the function in a sql statement.

SELECT firstchar(textfield) from table

这篇关于如何在 SQLite 中创建用户定义的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆