How would I go about wrapping an amount of queries in a transaction in C++? I'm working on Ubuntu 10, using this file:
#include "/usr/include/mysql/mysql.h"
with C++ to interact with a MySQL database.
EDIT: Right now I'm running queries through a small wrapper class, like so:
MYSQL_RES* PDB::query(string query)
{
int s = mysql_query(this->connection, query.c_str());
if( s != 0 )
{
cout << mysql_error(&this->mysql) << endl;
}
return mysql_store_result(this->connection);
}
MYSQL_ROW PDB::getarray(MYSQL_RES *res)
{
return mysql_fetch_row( res );
}
// example one
MYSQL_RES res = db->query( "SELECT * FROM `table` WHERE 1" );
while( MYSQL_ROW row = db->getarray( res ) )
{
cout << row[0] << endl;
}
If you use MySQL++, you get RAII transaction behavior with Transaction objects:
mysqlpp::Connection con( /* login parameters here */ );
auto query = con.query("UPDATE foo SET bar='qux' WHERE ...");
mysqlpp::Transaction trans(con);
if (auto res = query.execute()) {
// query succeeded; optionally use res
trans.commit(); // commit DB changes
}
// else, commit() not called, so changes roll back when
// 'trans' goes out of scope, possibly by stack unwinding
// due to a thrown exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With