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; +};