首页 / 操作系统 / Linux / Linux下MySQL 5.1编写UDF 并运行(Install)获取当前时间的毫秒数
Mysql 无法获取当前时间的毫秒数自行定制UDF,以提供current_ms方法1. 编写 C 文件#ifdef STANDARD#include <stdio.h>
#include <string.h>
#ifdef __WIN__
typedef unsigned __int64 ulonglong;
typedef unsigned __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 <sys/time.h>#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 timeval 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 -lmlibcurrent_ms.so : libcurrent_ms.o
ld -shared -o libcurrent_ms.so libcurrent_ms.o -fPIClibcurrent_ms.o : libcurrent_ms.cc
gcc -Wall $(MYSQLCFLAGS) $(MYSQLLIBS) -c libcurrent_ms.cc -o libcurrent_ms.o -fPICclean:
rm libcurrent_ms.o libcurrent_ms.soinstall:
cp libcurrent_ms.so /opt/soft/mysql/lib/mysql/plugin/3. make clean4. make 5. make install6. 登录mysql7. 创建UDFcreate function current_ms returns integer soname "libcurrent_ms.so";8. 使用 current_ms 方法select current_ms();9. 销毁UDFdrop function current_ms;