UDF,即user-defined function 。
Mariadb/Mysql数据库自带很多内置函数,比如select RAND();生成随机数。这个函数是可以用户自定义来完成特定的功能,比如与外部通信完成数据同步、复杂的计算方式等等。今天实验Mariadb数据库自定义函数UDF的使用,UDF是通过编译成.so文件来下实现的。
1、先自定义并编译c++函数testadd.cpp
c++使用别人的程序, c++方面笔者是文盲。.so文件是Linux下的程序函数库,即共享链接库,编译好的可以供其他程序使用的代码和数据。
#include <mysql.h>
extern "C" long long testadd(UDF_INIT *initid, UDF_ARGS *args, char *is_null, ch
ar *error)
{
int a = *((long long *)args->args[0]);
int b = *((long long *)args->args[1]);
return a + b;
}
extern "C" my_bool testadd_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
return 0;
}
使用g++编译:sudo g++ -shared -fPIC -I /usr/include/mysql -o testadd.so testadd.cpp,发现没有头文件mysql.h,初步怀疑是Mariadb数据库虽然兼容Mysql,但是配置文件等还是有区别的,于是搜索一番 sudo find / -name mysql.h :

编译的头文件目录错误了,这个就是Mariadb与Mysql的区别了。将命令更换为:sudo g++ -shared -fPIC -I /usr/include/mariadb -o testadd.so testadd.cpp 就可以得到编译文件testadd.so 。笔者在想能不能直接用头文件mariadb.h,在/usr/include/mariadb目录下没有找到,使用find命令在次级目录private下有一个,不知道能否使用,还是使用初级目录的mysql.h方便。

C语言:
2、查找数据库插件目录并将testadd.so拷贝到插件目录下
进入数据库,并查找关键字show variables like '%plugin%'; 可以找到插件目录(Mariadb数据库不同于Mysql), 拷贝testadd.so到插件目录下:sudo cp testadd.so /usr/lib/arm-linux-gnueabihf/mariadb19/plugin/ 。


3、登陆数据库并创建函数关联
根据testadd.so创建函数testadd ,create function testadd returns integer soname 'testadd.so';
使用函数testadd :select testadd(1,2); 就可实现1+2=3 。

网友评论