MySQLWrapper/MySQLWrapper.cpp

140 lines
2.6 KiB
C++
Raw Normal View History

2017-08-07 00:09:43 +08:00
#include "MySQLWrapper.h"
#include "MySQLInclude.h"
2017-08-07 10:55:28 +08:00
#include <string>
using namespace std;
/**********************
MySQL Result Class.
**********************/
2017-08-07 00:09:43 +08:00
struct MySQLResult::impl
{
MYSQL_RES* res;
};
MySQLResult::MySQLResult() : pimpl(new impl)
{
pimpl->res=nullptr;
}
MySQLResult::~MySQLResult()
{
if(pimpl->res)
{
mysql_free_result(pimpl->res);
pimpl->res=nullptr;
}
delete pimpl;
}
unsigned int MySQLResult::getNumFields()
{
return mysql_num_fields(pimpl->res);
}
uint64_t MySQLResult::getNumRows()
{
return mysql_num_rows(pimpl->res);
}
char* MySQLResult::getFieldName(int Index)
{
return mysql_fetch_fields(pimpl->res)[Index].name;
}
void MySQLResult::stepRow(const std::function<void(char** RowPtr, unsigned long* FieldLength)>& func)
{
MYSQL_ROW row;
while((row=mysql_fetch_row(pimpl->res)))
{
if(func)
{
func(row,mysql_fetch_lengths(pimpl->res));
}
}
}
2017-08-07 10:55:28 +08:00
/**********************
MySQL Connection Class.
**********************/
2017-08-07 00:09:43 +08:00
struct MySQLConn::impl
{
MYSQL m;
2017-08-07 10:55:28 +08:00
string lasterr;
2017-08-07 00:09:43 +08:00
};
MySQLConn::MySQLConn() : pimpl(new impl)
{
mysql_init(&(pimpl->m));
}
MySQLConn::~MySQLConn()
{
mysql_close(&(pimpl->m));
}
int MySQLConn::connect(const char* host, const char* user, const char* passwd, const char* db, unsigned int port)
{
2017-08-07 10:55:28 +08:00
if(mysql_real_connect(&(pimpl->m),host,user,passwd,db,port,NULL,0)==NULL)
{
pimpl->lasterr=mysql_error(&(pimpl->m));
return -1;
}
else
{
return 0;
}
2017-08-07 00:09:43 +08:00
}
int MySQLConn::exec(const std::string& SQLCommand, const std::function<void(MySQLResult&)>& func)
{
if(mysql_real_query(&(pimpl->m),SQLCommand.c_str(),SQLCommand.size())!=0)
{
/// Failed to Query
2017-08-07 10:55:28 +08:00
pimpl->lasterr=mysql_error(&(pimpl->m));
2017-08-07 00:09:43 +08:00
return -1;
}
2017-08-07 10:55:28 +08:00
2017-08-07 00:09:43 +08:00
MYSQL_RES* pres=mysql_store_result(&(pimpl->m));
if(pres==nullptr)
{
/// Store Result Returns Null.
if(getFieldCount()==0)
{
/// No Error.
return 1;
}
else
{
/// Failed to store result.
2017-08-07 10:55:28 +08:00
pimpl->lasterr=mysql_error(&(pimpl->m));
2017-08-07 00:09:43 +08:00
return -2;
}
}
MySQLResult res;
res.pimpl->res=pres;
2017-08-07 10:55:28 +08:00
if(func) func(res);
2017-08-07 00:09:43 +08:00
/// MySQL_RES will be released normally by MySQLResult::~MySQLResult()
return 0;
}
unsigned int MySQLConn::getFieldCount()
{
return mysql_field_count(&(pimpl->m));
}
uint64_t MySQLConn::getAffectedRows()
{
return mysql_affected_rows(&(pimpl->m));
}
2017-08-07 10:55:28 +08:00
const std::string& MySQLConn::getError()
{
return pimpl->lasterr;
}