MySQLWrapper/MySQLWrapper.cpp

154 lines
2.8 KiB
C++

#include "MySQLWrapper.h"
#include "MySQLInclude.h"
#include <string>
using namespace std;
/**********************
MySQL Result Class.
**********************/
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));
}
}
}
/**********************
MySQL Connection Class.
**********************/
struct MySQLConn::impl
{
MYSQL m;
string lasterr;
unsigned int lasterrcode;
};
MySQLConn::MySQLConn() : pimpl(new impl)
{
mysql_init(&(pimpl->m));
pimpl->lasterrcode=0;
}
MySQLConn::~MySQLConn()
{
mysql_close(&(pimpl->m));
}
int MySQLConn::connect(const std::string& host, const std::string& user, const std::string& passwd, const std::string& db, unsigned int port)
{
if(mysql_real_connect(&(pimpl->m),host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0)==nullptr)
{
_doUpdateError();
return -1;
}
else
{
return 0;
}
}
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
_doUpdateError();
return -1;
}
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.
_doUpdateError();
return -2;
}
}
MySQLResult res;
res.pimpl->res=pres;
if(func) func(res);
/// 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));
}
const std::string& MySQLConn::getError()
{
return pimpl->lasterr;
}
unsigned int MySQLConn::getErrCode()
{
return pimpl->lasterrcode;
}
///protected
void MySQLConn::_doUpdateError()
{
pimpl->lasterr=mysql_error(&(pimpl->m));
pimpl->lasterrcode=mysql_errno(&(pimpl->m));
}