From a5dcc01d2f96a894c358a2e40b6566ac796b0aa2 Mon Sep 17 00:00:00 2001 From: kiritow <1362050620@qq.com> Date: Tue, 14 Nov 2017 14:43:25 +0800 Subject: [PATCH] Update MySQL Error handling --- MySQLWrapper.cpp | 24 +++++++++++++++++++----- MySQLWrapper.h | 8 +++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/MySQLWrapper.cpp b/MySQLWrapper.cpp index 9b90daa..216d356 100644 --- a/MySQLWrapper.cpp +++ b/MySQLWrapper.cpp @@ -63,11 +63,13 @@ struct MySQLConn::impl { MYSQL m; string lasterr; + unsigned int lasterrcode; }; MySQLConn::MySQLConn() : pimpl(new impl) { mysql_init(&(pimpl->m)); + pimpl->lasterrcode=0; } MySQLConn::~MySQLConn() @@ -75,11 +77,11 @@ MySQLConn::~MySQLConn() mysql_close(&(pimpl->m)); } -int MySQLConn::connect(const char* host, const char* user, const char* passwd, const char* db, unsigned int port) +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,user,passwd,db,port,NULL,0)==NULL) + if(mysql_real_connect(&(pimpl->m),host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0)==nullptr) { - pimpl->lasterr=mysql_error(&(pimpl->m)); + _doUpdateError(); return -1; } else @@ -93,7 +95,7 @@ int MySQLConn::exec(const std::string& SQLCommand, const std::functionm),SQLCommand.c_str(),SQLCommand.size())!=0) { /// Failed to Query - pimpl->lasterr=mysql_error(&(pimpl->m)); + _doUpdateError(); return -1; } @@ -109,7 +111,7 @@ int MySQLConn::exec(const std::string& SQLCommand, const std::functionlasterr=mysql_error(&(pimpl->m)); + _doUpdateError(); return -2; } } @@ -137,3 +139,15 @@ 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)); +} diff --git a/MySQLWrapper.h b/MySQLWrapper.h index c580474..ccf8944 100644 --- a/MySQLWrapper.h +++ b/MySQLWrapper.h @@ -33,7 +33,7 @@ public: /// 数据库连接 /// 返回值: 0:连接正常, -1:连接错误 - int connect(const char* host,const char* user,const char* passwd,const char* db,unsigned int port); + int connect(const std::string& host, const std::string& user, const std::string& passwd, const std::string& db, unsigned int port); /// 执行SQL语句 /// 返回值: 1: 语句执行正常,无返回结果(func未执行) 0:语句执行正常,返回结果集交付func执行. -1:语句执行错误.(mysql_real_query失败) -2: 语句执行正确,获取结果出现错误 @@ -41,10 +41,16 @@ public: /// 获取错误信息 const std::string& getError(); + unsigned int getErrCode(); /// 当结果为空时用于判断数据库运行正常与否 unsigned int getFieldCount(); uint64_t getAffectedRows(); + +protected: + /// 更新错误信息 + void _doUpdateError(); + private: struct impl; impl* pimpl;