C + + MySQL transaction commit and rollback

Source: Internet
Author: User

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;&LT;&LT;&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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.