C ++中的MySQL用户定义函数

时间:2017-04-11 09:30:02

标签: c++ mysql-udf

我正在尝试运行用C ++编写的MySQL UDF。它编译得很好并生成正确的输出,但它在输出后会产生大量的垃圾。我想知道这个垃圾的原因以及我如何解决这个问题?我附上了我的代码和输出的截图。

#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include "mysql-connector-c-6.1.9-linux-glibc2.5-x86_64/include/mysql.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/mysql_connection.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/sqlstring.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/datatype.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset_metadata.h"
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/exception.h"

using namespace std;

extern "C" {
    char *hello_world (UDF_INIT *initid, UDF_ARGS *args,char *result, unsigned long length,char *is_null, char *error);
    my_bool hello_world_init (UDF_INIT *initid, UDF_ARGS *args, char *message);
    void hello_world_deinit (UDF_INIT *initid);
    //template <typename T>  T adder (UDF_INIT *initid, UDF_eARGS *args,string result, unsigned long length,string is_null, string error,T v);
}

char *hello_world (UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long length, char *is_null, char *error)
{
    string res;
    res = args->args[0];
    res.append(" hello");
    char *c = new char[res.size()];
    strcpy(c, res.c_str());
    return c;
}

my_bool hello_world_init (UDF_INIT *initid, UDF_ARGS *args, char *message)
{
    return 0;
    //cout<<"success"<<endl;
}

void hello_world_deinit (UDF_INIT *initid)
{
    return;
}

enter image description here

1 个答案:

答案 0 :(得分:3)

hello_world功能的签名是错误的。第四个参数应该是

unsigned long *length

该指针指向的值必须设置为返回字符串的长度。

char *c = new char[res.size() + 1];
strcpy(c, res.c_str());
*length = res.size();
return c;