This examples shows how the ScopedTransaction object operates in different situations.
#include <SimpleDB.h> int main(int argc, char ** argv) { using namespace SimpleDB; try { Database db("simpledb-examples"); { /* * This transaction is not committed, so the following query * will rollback. */ ScopedTransaction trans(db); db.voidQuery("INSERT INTO sessions VALUES (5,'wont commit', datetime('now'))"); } { /* * This transaction is not committed, so all changes * within it's scope will be rolled back, even though the * child transaction is committed. */ ScopedTransaction trans(db); { ScopedTransaction trans(db); db.voidQuery("INSERT INTO sessions VALUES(5, 'try', datetime('now'))"); trans.commit(); } } /* * This query is not within the scope of any transaction, * so the database connection will be in autocommit mode and so * this query will be committed. */ db.voidQuery("INSERT INTO sessions VALUES(5, 'autocommit', datetime('now'))"); { /* * This transaction and it's child are committed, therefore these * queries will be committed */ ScopedTransaction trans(db); { ScopedTransaction trans(db); std::cerr << "num: " << db.getTransactionCount() << std::endl; db.voidQuery("INSERT INTO sessions VALUES(5, 'commit', datetime('now'))"); trans.commit(); } std::cerr << "num: " << db.getTransactionCount() << std::endl; trans.commit(); } std::cerr << "num: " << db.getTransactionCount() << std::endl; { ScopedTransaction trans(db); trans.rollback(); /* * Throws an exception because the transaction is still in scope * but it is being rolled back */ db.voidQuery("INSERT INTO sessions VALUES(5, 'try', datetime('now'))"); } } catch (const std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } }