linux下mysql扩展,自定义函数实现(…

Adding a New User-Defined Function
"The MySQL source distribution includes a file sql/udf_example.c that defines 5 new functions"
下载mysql在目录中可看到sql/udf_example.c,我们可以参考。
流程:编译自己的动态库=>创建函数
首先建立一个简单的测试函数库,返回值为字符串类型
代码为:
//mtest.h
#ifndef MTEST_H_
#define MTEST_H_
#include <my_global.h>
#include <mysql.h>

my_bool mtest_init(UDF_INIT *initid, UDF_ARGS *args, char *message);

char *mtest(UDF_INIT *initid, UDF_ARGS *args,
          char *result, unsigned long *length,
          char *is_null, char *error);

void mtest_deinit(UDF_INIT *initid);

#endif
//mtest.c
#include <string.h>
#include "mtest.h"

my_bool mtest_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
if(0 != args->arg_count){
strncpy(message, "mtest has no arguments", strlen("mtest has no arguments") + 1);
return 1;
}

initid->ptr = calloc(1, 1024);

return 0;
}

char *mtest(UDF_INIT *initid, UDF_ARGS *args,
          char *result, unsigned long *length,
          char *is_null, char *error)
{
char *ps = "mysql plugin string type test.";
*length = strlen(ps);

memcpy(initid->ptr, ps, *length + 1);

return initid->ptr;
}

void mtest_deinit(UDF_INIT *initid)
{
free(initid->ptr);
}
编译为libmtest.so,复制到plugin目录下
重启mysql
$mysql -h127.0.0.1 -u root -P3306
//create
mysql> CREATE FUNCTION mtest RETURNS STRING SONAME 'libmtest.so';
mysql> select mtest();
+--------------------------------+
| mtest()                         |
+--------------------------------+
| mysql plugin string type test. | 
+--------------------------------+
1 row in set (0.02 sec)

//drop
mysql> DROP FUNCTION mtest;


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值