Add Transaction support

This commit is contained in:
Kirigaya Kazuto 2017-11-23 14:48:10 +08:00
parent 5de3e0c295
commit 9ae86e4127
2 changed files with 84 additions and 0 deletions

58
MySQLTransaction.cpp Normal file
View File

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

26
MySQLTransaction.h Normal file
View File

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