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.
#创建账户表 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 failure SELECT * FROM account; #第一步 Close transaction autocommit mode SET autocommit=0; #第二步 Start transaction START TRANSACTION; #第三步 Discovery Remittance failed, Rolling a transaction back rollback | | Remittances successfully commit the event #假设语法错误 update account set money=money-500 where username= ' A '; select * from account; update account set&nbsP;money=money+200 where username= ' B '; rollback; #第四步 Restore automatic submission of MySQL database SET autocommit=1; SELECT * FROM account; /*b Receive remittance failed */ 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;
Note:
Use if not exists to create a data table interpretation
MySQL Transaction implementation method steps