Requirements Description:
Case background: In the course of bank transfer, accidents are unavoidable. To avoid unnecessary losses caused by an accident, the transaction is handled in the same way:
A account has an existing balance of $1000 and a transfer of $500 to a balance of 200 B accounts. Possible for a reason:
A account has an error while deducting the transfer amount, using a transaction rollback to return to the initial state
A after the account has successfully deducted the transfer amount, the B account adds the transfer amount error, using the transaction rollback to the initial state
Tip: First build the data table account, the field includes the name (username), the balance (money), and then use the transaction to handle the above two cases respectively.
[SQL]View PlainCopy
- #创建账户表
- CREATE TABLE IF not EXISTS account (
- ID INT (one)not NULL auto_increment PRIMARY KEY,
- Username VARCHAR (+)not NULL,
- Money DECIMAL (9,2)
- ) Engine=innodb;
- #插入用户数据
- INSERT into account ( Username,money)VALUES (' A ', 1000.00);
- INSERT into account ( Username,money)VALUES (' B ', 200.00);
- /* Transaction Processing */
- # A account remittance failed
- SELECT * from account ;
- #第一步 Turn off transaction autocommit mode
- SET autocommit=0;
- #第二步 Start a transaction
- START TRANSACTION;
- #第三步 Find the remittance failed, rollback the transaction ROLLBACK | | Remittance successfully commits the event
- #假设语法错误
- UPDATE account SET money=money-500 WHERE username=' A ';
- SELECT * from account ;
- UPDATE account SET money=money+200 WHERE username=' B ';
- ROLLBACK;
- #第四步 Restore the automatic submission of MySQL database
- SET autocommit=1;
- SELECT * from account ;
- /*B Receive remittance failure */
- SELECT * from account;
- SET autocommit = 0;
- START TRANSACTION;
- UPDATE account SET money=money-500 WHERE username=' A ';
- SELECT * from account ;
- #假设语法错误
- UPDATE account SET money=money+200 WHERE username =' B ';
- ROLLBACK;
- SET autocommit = 1;
- SELECT * from account ;
- #清除数据
- <pre name="code" class="sql" >TRUNCATE Account;
MySQL Transaction implementation method steps