mysql输出接口,包扩重连接
Output_mysql.h
// Output_mysql.h: interface for the Output_mysql class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_OUTPUT_MYSQL_H__5492A513_A87A_46B9_B8A5_2209B57E2E82__INCLUDED_)
#define AFX_OUTPUT_MYSQL_H__5492A513_A87A_46B9_B8A5_2209B57E2E82__INCLUDED_
#include "Log.h"
#include "mysql.h"
// mysql输出
class Output_mysql
{
public:
// @brief 数据库插入
bool insert(char* buf);
// @brief 初始化
bool init();
Output_mysql();
virtual ~Output_mysql();
private:
//mysql连接
MYSQL _mysql;
};
#endif // !defined(AFX_OUTPUT_MYSQL_H__5492A513_A87A_46B9_B8A5_2209B57E2E82__INCLUDED_)
Output_mysql.cpp
// Output_mysql.cpp: implementation of the Output_mysql class.
//
//////////////////////////////////////////////////////////////////////
#include "Output_mysql.h"
#include "Log.h"
#include "Main_config.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Output_mysql::Output_mysql()
{
}
Output_mysql::~Output_mysql()
{
mysql_close(&_mysql);
}
bool Output_mysql::init()
{
bool ret = true;
std::string ipAddress;
std::string username;
std::string passwd;
std::string database;
//读取数据库配置
ipAddress = Main_config::instance().get_config().Read("MYSQL_IP", ipAddress);
username = Main_config::instance().get_config().Read("MYSQL_USER", username);
passwd = Main_config::instance().get_config().Read("MYSQL_PASSWD", passwd);
database = Main_config::instance().get_config().Read("MYSQL_DATABASE", database);
//mysql 初始化
if(!mysql_init(&_mysql))
{
FATAL("mysql_init failed");
return false;
}
//mysql设置重新连接
char reconnect = 1;
if(mysql_options(&_mysql, MYSQL_OPT_RECONNECT, &reconnect) != 0)
{
FATAL("MYSQL_OPTION ERROR");
return false;
}
//mysql 连接
if(!mysql_real_connect(&_mysql, ipAddress.c_str(), username.c_str(), passwd.c_str(), database.c_str(), 0, NULL, 0))
{
FATAL("mysql_real_connect failed");
return false;
}
return ret;
}
bool Output_mysql::insert(char* buf)
{
bool ret = true;
char db_cmd[DB_CMD_LEN];
snprintf(db_cmd, DB_CMD_LEN, "%s", buf);
if(mysql_ping(&_mysql) != 0)
{
NOTICE("reconnect mysql");
}
int ret_val = mysql_real_query(&_mysql, db_cmd, (unsigned int)strlen(db_cmd));
if(ret_val)
{
WARNING("insert failed: " << ret_val);
}
else
{
NOTICE("insert success: " << db_cmd);
}
return ret;
}