#define DB_HOST "172.25.2.50"
#define DB_PORT 3306
#define DB_USER "root"
#define DB_PASSWD "123456"
#define DB_NAME "db_dev"
#include <mysql.h>
#include <list>
#define MIN_CONNECT_SIZE 10
#define MAX_CONNECT_SIZE 20
using namespace std;
class DBMgr
{
public:
DBMgr();
~DBMgr();
private:
MYSQL* CreateConnect(); //create a sql connect
public:
bool InitPool(); //initialize memory pool
MYSQL* GetConnect(); //get a sql connect
bool ReleaseConnect(MYSQL* mysql); //release a sql connect
MYSQL_RES* GetQuery(MYSQL* mysql, const char* query); //get a sql query
void ReleaseQuery(MYSQL_RES* res); //release sql query
bool Close();
public:
/*
bool Initialize();
bool Query(const char* str);
*/
private:
list<MYSQL*> m_sql_pool;
unsigned int m_curSize;
/*
MYSQL* m_mysql;
MYSQL_RES* m_res;
MYSQL_ROW m_row;
*/
};
extern DBMgr* g_DBMgr;
#include "DBMgr.h"
#include <stdio.h>
DBMgr::DBMgr()
{
}
DBMgr::~DBMgr()
{
}
bool DBMgr::InitPool()
{
for (int i = 0; i < MIN_CONNECT_SIZE; ++i)
{
MYSQL* mysql;
mysql = CreateConnect();
if (mysql)
{
m_sql_pool.push_back(mysql);
++m_curSize;
}
else{
printf("[InitPool] No.%d connect to sql failed", i);
}
}
return true;
}
MYSQL* DBMgr::CreateConnect()
{
MYSQL* mysql;
mysql = mysql_init((MYSQL*)NULL);
if (NULL == mysql){
printf("[CreateConnect] mysql init failed");
return (MYSQL*)NULL;
}
if (mysql_real_connect(mysql, DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT, NULL, 0)){
return mysql;
}
return (MYSQL*)NULL;
}
MYSQL* DBMgr::GetConnect()
{
if (m_sql_pool.size())
{
MYSQL* mysql = m_sql_pool.front();
m_sql_pool.pop_front();
printf("[GetConnect] pool size: %d\n", m_sql_pool.size());
return mysql;
}
else{
if (m_curSize < MAX_CONNECT_SIZE)
{
MYSQL* mysql;
mysql = CreateConnect();
if (mysql){
++m_curSize;
printf("[GetConnect] pool is empty, create a new connect\n");
return mysql;
}
}
}
printf("[GetConnect] max connect size, please try again!\n");
return (MYSQL*)NULL;
}
bool DBMgr::ReleaseConnect(MYSQL* mysql)
{
if (m_sql_pool.size() < MAX_CONNECT_SIZE)
{
m_sql_pool.push_back(mysql);
printf("[ReleaseConnect] pool size: %d\n", m_sql_pool.size());
return true;
}
else{
printf("[ReleaseConnect] sql pool is overflow!");
}
return false;
}
MYSQL_RES* DBMgr::GetQuery(MYSQL* mysql, const char* query)
{
int result = mysql_real_query(mysql, query, strlen(query));
if (result){
printf("[GetQuery] select error %d: %s !\n", mysql_errno(mysql), mysql_error(mysql));
return (MYSQL_RES*)NULL;
}
return mysql_store_result(mysql);
}
void DBMgr::ReleaseQuery(MYSQL_RES* res)
{
mysql_free_result(res);
}
bool DBMgr::Close()
{
while (!m_sql_pool.empty())
{
MYSQL* mysql = m_sql_pool.front();
if (mysql)
{
mysql_close(mysql);
}
m_sql_pool.pop_front();
}
//mysql_free_result(m_res);
//mysql_close(m_mysql);
printf("[close] db connection close!\n");
return true;
}