Index
There are three mutually exclusive ways to implement transactions. They cannot be combined together. Pick one, and use it exclusively.
void move_money(const x::sql::connection &conn, int from_account, int to_account, double amount) { conn->autocommit(false); auto statement=conn->prepare("INSERT INTO ledger(account_id, amount) VALUES(?, ?)"); conn->execute(from_account, -amount); conn->execute(to_account, amount); conn->commit(); conn->autocommit(true); }
autocommit() changes the connection's autocommit
mode. The default true setting commits each
statement to the database, automatically. After turning it off,
an explicit commit() commits all executed
statements; and rollback() rolls them back.
Afterwards, the next statement creates another transaction, collecting
statements to be
commit()ed or
rollback()ed.
Changing the autocommit setting back to true
reenables automatic commit of every transaction.
commit() and
rollback() take an optional
bool parameter, which defaults to a
false value. Explicitly setting the parameter to
true has the effect of commiting or rolling back
the transaction and reenabling autocommit mode, in one operation.