注意事项:
Tools->Options->Directories增加mysql安装目录下的include/lib;
libmySQL.dll也要COPY到DEBUG目录下,LR使用时,同MonitorTest.dll一起复制到脚本目录下;
VC++代码:
MonitorTest.cpp
#include "stdafx.h"
#include "MonitorTest.h"
#include "stdlib.h"
#include "winsock.h"
#include "mysql.h"
#include "stdio.h"
//stdio.h头文件必须要放在stdafx.h头文件后
MYSQL conn;
MYSQL_RES *p_res_ptr=NULL;
MYSQL_ROW sqlrows;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
int init_mysql_connection(char *str_server,char *str_username,char *str_pwd,char *str_db)
{
mysql_init(&conn);
printf("\nSuccess to initate MySQL connection\n");
if (!mysql_real_connect(&conn,str_server,str_username,str_pwd,str_db,0,NULL,0))
{
printf( "Failed to connect to MySQL: Error: %s\n", mysql_error(&conn));
return 1;
}
else
{
printf("\nLogged on to %s sucessfully\n",str_server);
return 0;
}
}
int close_mysql_connection()
{
mysql_free_result(p_res_ptr);
printf("\nClose connection");
mysql_close(&conn);
return 0;
}
int get_mysql_query_data(char *str_query,char *str_data)
{
mysql_real_query(&conn, str_query, (UINT)strlen(str_query));
MYSQL_RES * res ;
MYSQL_ROW row;
res = mysql_use_result( &conn ) ;
row = mysql_fetch_row( res );
strcpy(str_data,row[1]);
mysql_free_result(res);
return 0;
}//此函数的参数str_query,查询后的结果必须唯一,主要用来查看show status的变量值
//////////////////////////////////////////////////////////////////////////////////
MonitorTest.def
LIBRARY "MonitorTest"
DEscrīptION 'MonitorTest Windows Dynamic Link Library'
EXPORTS
init_mysql_connection @1
close_mysql_connection @2
get_mysql_query_data @3
LR中的脚本:
#include "web_api.h"
double atof (const char * string ); //使用atof前需先声明
Action()
{
lr_load_dll("MonitorTest.dll");
int i=0;
double f;
char *str_data;
str_data=(char *)malloc(20*sizeof(char));
i= init_mysql_connection("192.168.146.50","root","111111","mysql");
//lr_output_message("%d",i);
for(;;)
{
i = get_mysql_query_data("show status like 'Uptime';",str_data);
//lr_output_message("%d",i);
lr_output_message("%s",lr_eval_string(str_data));
f = atof(str_data);
lr_output_message("%.2f",f);
lr_user_data_point("Uptime",f);
lr_think_time(5);
}
close_mysql_connection();
return 0;
}