C++:MySQL事务

Jos*_*osh 4 c++ mysql transactions

我如何在C++中用事务包装大量的查询?我正在使用这个文件在Ubuntu 10上工作:

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

使用C++与MySQL数据库进行交互.

编辑:现在我正在通过一个小的包装器类运行查询,如下所示:

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;
  }
Run Code Online (Sandbox Code Playgroud)

War*_*ung 6

如果您使用MySQL ++,您将获得Transaction对象的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
}
Run Code Online (Sandbox Code Playgroud)