当前位置:网站首页>MySQL transaction

MySQL transaction

2022-06-11 10:03:00 Don't want to be a programmer

Business : Either they all succeed 、 Or they all failed ( For example, two people transfer money )

A set of sql Put it in a batch to execute

Business principles :ACID principle

  • Atomicity (Atomicity): For the same transaction , Or both , Or it's not done
  • Uniformity (Consistency):( Final consistency ) For a transaction, the state before and after the operation is consistent
  • Isolation, (Isolation): For multiple users at the same time , It is mainly to exclude the influence of other foods on this affair
  • persistence (Durability): The data after the transaction ends will not be lost due to external reasons ( The transaction was not committed , Return to the original state , The transaction has been committed , Persist to database )

The isolation level of the transaction :

  • Dirty reading : A transaction reads uncommitted data from another transaction
  • Non repeatability : Read a row of data in a table in a transaction , Multiple reads result is different .( This is not necessarily a mistake , It's just that on some occasions it's not right )
  • Virtual reading ( Fantasy reading ): It refers to the data inserted by other transactions in a transaction , Leading to inconsistent reading before and after .( It's usually the line effect , One more line )

Perform transactions
– mysql Automatic transaction commit is enabled by default

set autocommit = 0 /* close */
set autocommit = 1 /* Turn on ( default )*/
--  Handle transactions manually 
--  The transaction open 
start transaction -- Mark the beginning of a transaction , From after sql All in one transaction 

insert **
insert **

--  Submit : Persistence ( success !)
commit

-- Roll back : Back to the original ( Failure !)
rollback

-- End of transaction 
set autocommit = 1 -- Turn on auto submit 

-- understand 
savepoint  Save point name  -- Set a save point for a transaction 

rollback to savepoint  Save point name  -- Roll back to savepoint 

release savepoint  Save point name  -- Undo savepoint 

Analog transfer

create database shop character set utf8 collate utf8_general_ci
use shop
create table account
(
	id int(3)not null auto_increment ,
	name varchar(20) not null,
	money decimal(9,2) not null,
	primary key (id)
)engine=InnoDB default charset = utf8;

Insert two rows of data
 Insert picture description here
Simulate transfer transactions

set autocommit = 0; --1  Turn off auto submit 
start transaction --2  Start a transaction 
update account set money=money-500 where name='ming'--3
update account set money=money+500 where name='hao'--4
commit;--5
rollback;--6
set autocommit = 1;--7

One sentence at a time , In the implementation of the 3、4 After sentence , If direct commit Can not rollback.

原网站

版权声明
本文为[Don't want to be a programmer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111001157072.html