MySQLWrapper/MySQLWrapper.cpp

112 lines
2.1 KiB
C++
Raw Normal View History

2017-08-07 00:09:43 +08:00
#include "MySQLWrapper.h"
#include "MySQLInclude.h"
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));
}
}
}
struct MySQLConn::impl
{
MYSQL m;
};
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)
{
return (mysql_real_connect(&(pimpl->m),host,user,passwd,db,port,NULL,0)==NULL)?0:-1;
}
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
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.
return -2;
}
}
MySQLResult res;
res.pimpl->res=pres;
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));
}