C ++: MySQL transactions

How can I wrap the number of requests in a transaction in C ++? I am working on Ubuntu 10 using this file:

#include "/usr/include/mysql/mysql.h"

with C ++ to interact with the MySQL database.

EDIT: right now I am running queries through a small wrapper class, for example:

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;
  }
+3
source share
2 answers

You can always just run START TRANSACTION// COMMIT// manually.

Another way would be to create a wrapper class that launches START TRANSACTION in the constructor, provides commit / rollback functions, and, depending on your use case, rolls back when destroyed.

+3
source

MySQL++, RAII :

mysqlpp::Connection con( /* login parameters here */ );
mysqlpp::Query query = con.query("UPDATE foo SET bar='qux' WHERE ...");
mysqlpp::Transaction trans(con);
mysqlpp::StoreQueryResult res = query.execute();
// do more random things
if (commit_path) {
    trans.commit();  // commit DB changes
}
else {
    // commit() not called, so changes roll back when 'trans' goes out of scope
}
+5

Source: https://habr.com/ru/post/1786708/


All Articles