日期:2014-05-16  浏览次数:20748 次

mysql udf 的实现过程
首先编写一个实现curl提交的udf,文件名起名为lib_mysqludf_clearcache.c
mysql udf 编写的相关规范可以查看mysql官方手册
http://dev.mysql.com/doc/refman/5.1/zh/extending-mysql.html#adding-functions


#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || defined(WIN32)
#define DLLEXP __declspec(dllexport) 
#else
#define DLLEXP
#endif

#ifdef STANDARD
#include <string.h>
#include <stdlib.h>
#include <time.h>
#ifdef __WIN__
typedef unsigned __int64 ulonglong;
typedef __int64 longlong;
#else
typedef unsigned long long ulonglong;
typedef long long longlong;
#endif /*__WIN__*/
#else
#include <my_global.h>
#include <my_sys.h>
#endif
#include <mysql.h>
#include <m_ctype.h>
#include <m_string.h>
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

#include <ctype.h>


#define DEST_URL "http://www.web.com/"

my_bool clear_cache_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  return 0;
}

void clear_cache_deinit(UDF_INIT *initid)
{

}

char *clear_cache(UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long *length, char *is_null, char *error)
{
    CURL *curl;  
    CURLcode res;  
      
    // 初始化curl  
    curl = curl_easy_init();  
      
    if(curl != NULL)  
    {  
        // 设置目标url  
        curl_easy_setopt(curl,CURLOPT_URL,DEST_URL);  
          
        // 输出header头部信息  
        curl_easy_setopt(curl,CURLOPT_HEADER,0);  
          
        // 执行操作  
        res = curl_easy_perform(curl);  
          
        // 执行回收资源  
        curl_easy_cleanup(curl);  
    } 
	
	return 0;
}



然后编译生成so文件
gcc  -I /usr/include/mysql -shared  lib_mysqludf_clearcache.c  -o lib_mysqludf_clearcache.so -lcurl

第三步把lib_mysqludf_clearcache.so复制到mysql的插件目录
cp lib_mysqludf_clearcache.so /usr/lib/mysql/plugin/

第四步进入mysql
执行
CREATE FUNCTION clear_cache RETURNS INTEGER SONAME 'lib_mysqludf_clearcache.so';

然后执行 select clear_cache()查看自定义函数是否执行成功