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

MySQL transaction

2022-06-21 15:28:00 gaoZhuanMing

1. The nature of the transaction

  • Atomicity Atomicity): All operations in a transaction , Or it's all done , Or not at all , It doesn't end in the middle .
  • Uniformity Consistency): Before and after transaction start , The integrity of the data is not compromised , That is to say, it completely conforms to all the preset rules .
  • Isolation, Isolation): Prevent data inconsistency caused by cross execution of multiple concurrent transactions .
  • persistence Durability): When the business is over , Changes to data are permanent , Even if the system fails, it will not be lost .

2. The transaction operations

Automatically submit by default : Each statement is a transaction .

#  Turn off auto submit 
SET AUTOCOMMIT=0;

#  perhaps , Explicitly starts a transaction 
BEGIN;

#  Submit 
COMMIT;

#  Roll back 
ROLLBACK;

#  Declare a hold point 
SAVEPOINT savepoint_name;

#  Rollback to the specified retention point 
ROLLBACK TO savepoint_name;

#  Release the hold :COMMIT, ROLLBACK  Then it will be released automatically 
RELEASE SAVEPOINT savepoint_name;

3. Isolation,

Problems with concurrent transactions :

  • Dirty reading : Business tx1 Read the transaction tx2 Updated but not yet submitted data , Then if tx2 Roll back , be tx1 What you read is temporarily invalid content .
  • It can't be read repeatedly : Business tx1 Read a field , Then transaction tx2 Updated the field , Then business tx1 This field is read again , Business tx1 The contents read before and after are inconsistent .
  • Fantasy reading : Business tx1 First, query a table , Then transaction tx2 Some new rows have been inserted into the table , If the transaction tx1 Read the table again , You will find new lines .

Isolation level :

  • READ UNCOMMITTED: Dirty reading will occur 、 It can't be read repeatedly 、 Fantasy reading .
  • READ COMMITTED: Avoid dirty reading , But it can not solve the problem of unrepeatable reading and unreal reading .
  • REPEATABLE READ( Default ): Avoid dirty reading 、 It can't be read repeatedly , But I can't understand the unreal reading .
  • SERIALIZABLE: Can solve all the problems .
#  View the current isolation level 
SELECT @@tx_isolation;

#  Set the isolation level of the current session 
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
原网站

版权声明
本文为[gaoZhuanMing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221145446520.html