我该如何在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;
}发布于 2011-01-20 23:56:50
你可以直接运行START TRANSACTION / COMMIT / ...手动。
另一种方法是创建一个包装类,它在构造函数中运行START TRANSACTION,提供提交/回滚函数,并根据您的用例在销毁时执行回滚。
发布于 2011-01-21 21:00:04
如果使用MySQL++,则可以通过Transaction objects获得RAII事务行为
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.https://stackoverflow.com/questions/4749211
复制相似问题