Prior to the operation of the database, it was found that some content should be submitted as a transaction, rather than being submitted separately, which would require these operations to be handled as a transaction. And I have previously written a simple database operation, because MySQL default is auto-commit, we need to use Api--mysql_commit ().
Mysql_commit (mysql* MYSQL, My_bool mode);
A mode of 1 indicates off when the On,mode is 0.
After the automatic submission is turned off, we will need to manually submit the operation, and this is what we need, for a series of operations, if all successful, then we will put them up, if the failure to perform rollback, here need to use two additional APIs:
Mysql_commit ()
Commits the transaction.
Mysql_rollback ()
Rolls back the transaction.
Example code:
Void mydb::test () {int i = 0;std::string sql_1 = "Insert into user (id,username,password,level) values ( 1, ' username ', ' psd ', 1 ); "; std::string sql_2 = "Insert into user (id,username,password,level) values ( 1, ' username ', ' psd ', ' 1 '); /std::string sql_2 = "update user set id = 4 where id = 5; "; Int on = 1;int off = 0;mysql_autocommit (Connection,off); Mysql_autocommit ( Connection,off); if (mysql_query (Connection,sql_1.c_str ())) {std::cout << "sql_1 was Error "&NBSP;<<&NBSP;STD::ENDL;I&NBSP;=&NBSP;1;} if (mysql_query (Connection,sql_2.c_str ())) {std::cout << "Sql_2 was error" < < std::endl;i = 1;} if (i == 1) {mysql_rollback (connection);} Else{mysql_commit (connection);} Mysql_autocommit (Connection,on);}
This code can be directly used in the previous Linux C + + access to the MySQL database (2), because I set the ID before the primary key, can not be duplicated, so the final result is sql_2 execution error, the previous operation all rolled back.
I did some tests on my own and I haven't found any problems yet.
C + + MySQL transaction commit and rollback