Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Transactions using C++?

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;
  }
like image 531
Josh Avatar asked Dec 29 '22 02:12

Josh


1 Answers

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.
like image 137
Warren Young Avatar answered Jan 12 '23 17:01

Warren Young