Linux下MySQL 5.1编写UDF 并运行(Install)获取当前时间的毫秒数

2014-11-24 09:17:31 · 作者: · 浏览: 0

Mysql 无法获取当前时间的毫秒数


自行定制UDF,以提供current_ms方法


1. 编写 C 文件


#ifdef STANDARD


#include
#include
#ifdef __WIN__
typedef unsigned __int64 ulonglong;
typedef unsigned __int64 longlong;
#else
typedef unsigned long long ulonglong;
typedef long long longlong;
#endif /*__WIN__*/
#else
#include
#include
#endif
#include
#include
#include
#include


#ifdef HAVE_DLOPEN


/* These must be right or mysqld will not find the symbol! */


extern "C" {
my_bool current_ms_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
void current_ms_deinit(UDF_INIT *initid);
longlong current_ms(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error);
}


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


void current_ms_deinit(UDF_INIT *initid) {
}


longlong current_ms(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) {
struct timeva l tv;
gettimeofday(&tv, NULL);
longlong value = tv.tv_sec*1000 + (tv.tv_usec/1000);
return value;
}


#endif /* HAVE_DLOPEN */


2. 编写 Makefile 文件


#其中 mysql 的安装位置要根据您的机器自行修改 (可用 mysql_config --cfalgs mysql_config --libs 来获取)


MYSQLCFLAGS = -I/opt/soft/mysql/include/mysql -DUNIV_LINUX -DUNIV_LINUX
MYSQLLIBS = -rdynamic -L/opt/soft/mysql/lib/mysql -lmysqlclient -lz -lcrypt -lnsl -lm


libcurrent_ms.so : libcurrent_ms.o
ld -shared -o libcurrent_ms.so libcurrent_ms.o -fPIC


libcurrent_ms.o : libcurrent_ms.cc
gcc -Wall $(MYSQLCFLAGS) $(MYSQLLIBS) -c libcurrent_ms.cc -o libcurrent_ms.o -fPIC


clean:
rm libcurrent_ms.o libcurrent_ms.so


install:
cp libcurrent_ms.so /opt/soft/mysql/lib/mysql/plugin/


3. make clean


4. make


5. make install


6. 登录mysql


7. 创建UDF


create function current_ms returns integer soname 'libcurrent_ms.so';


8. 使用 current_ms 方法


select current_ms();


9. 销毁UDF


drop function current_ms;