From 9ae86e4127930358c333f7f843ca06312e2cba55 Mon Sep 17 00:00:00 2001 From: kiritow <1362050620@qq.com> Date: Thu, 23 Nov 2017 14:48:10 +0800 Subject: [PATCH] Add Transaction support --- MySQLTransaction.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++ MySQLTransaction.h | 26 ++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 MySQLTransaction.cpp create mode 100644 MySQLTransaction.h diff --git a/MySQLTransaction.cpp b/MySQLTransaction.cpp new file mode 100644 index 0000000..2a43ba1 --- /dev/null +++ b/MySQLTransaction.cpp @@ -0,0 +1,58 @@ +#include "MySQLTransaction.h" + +Transaction::Transaction(MySQLConn& MySQLConnection) : conn(MySQLConnection) +{ + _isReady=false; + _operated=false; + if(conn.exec("start transaction",nullptr)<0) + { + /// SQL execute error. + } + else + { + _isReady=true; + } +} + +Transaction::~Transaction() +{ + if(!_operated) + { + rollback(); + } +} + +int Transaction::commit() +{ + if(_operated) return -2; + + if(conn.exec("commit",nullptr)<0) + { + return -1; + } + else + { + _operated=true; + return conn.getAffectedRows(); + } +} + +int Transaction::rollback() +{ + if(_operated) return -2; + + if(conn.exec("rollback",nullptr)<0) + { + return -1; + } + else + { + _operated=true; + return conn.getAffectedRows(); + } +} + +bool Transaction::isReady() const +{ + return _isReady; +} diff --git a/MySQLTransaction.h b/MySQLTransaction.h new file mode 100644 index 0000000..b962ff5 --- /dev/null +++ b/MySQLTransaction.h @@ -0,0 +1,26 @@ +#include "MySQLWrapper.h" + +class Transaction +{ +public: + /// Start Transaction on construct. + Transaction(MySQLConn& MySQLConnection); + + /// Rollback transaction on destruct. If commit() or rollback() is called, this function will not execute any sql. + ~Transaction(); + + /// NOTE: A Transaction can only call commit() or rollback() once, until it calls start commit again. + /// Commit transaction. Equals to SQL: COMMIT + /// ReturnValue: -1 SQL Error. -2 Operated >=0 Affected Rows + int commit(); + /// Rollback transaction. Equals to SQL: ROLLBACK + /// ReturnValue: -1 SQL Error. -2 Operated >=0 Affected Rows + int rollback(); + + /// Check if a Transaction object is ready. If it is ready, then a transaction has started. + bool isReady() const; +private: + MySQLConn& conn; + bool _isReady; + bool _operated; +};