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

SQL transaction

2022-06-12 05:04:00 vihem


One 、 What is business ?

The business is A logical set of operations , yes It consists of a series of operations to access and update data in the system Program execution logic unit (Unit).
Or both , Either not .
 

A classic example ------ Transfer accounts :
A The user to B User transfer 100 element , There are two data operations involved :A Decrease in user accounts 100,B User account increase 100. If the database crashes between two operations , Lead to A Less B No increase , That's the trouble . therefore :
Transaction is to ensure that both operations are completed , Or it's not done .

 

Two 、 Four characteristics of transactions (ACID)

 Insert picture description here

1. Atomicity (Atomicity)

finger Transactions are the smallest unit of execution , Division is not allowed . The atomicity of transactions ensures that actions Or both , Either not .

2. Uniformity (Consistency)

finger Before and after the execution of the transaction , Data consistency , Multiple transactions read the same data with the same result .

The result of transaction execution must be Change the database from one consistency state to another consistency state , So when the database contains only the results of a successful transaction commit , We can say that the database is in a consistent state .
And if the database system fails during operation , Some transactions are interrupted before they are completed , Some of the changes made to the database by these unfinished transactions have been written to the physical database , The database is in an incorrect state , Or inconsistent state .

3. Isolation, (Isolation)

finger In a concurrent environment , Concurrent transactions are isolated from each other , The execution of one transaction cannot be interfered by other transactions , The database between concurrent transactions is independent .

When different transactions manipulate the same data concurrently , Each transaction has its own complete data space , That is, the operations and data used within a transaction are isolated from other concurrent transactions , Concurrent execution Transactions should not interfere with each other .

4. persistence (Durability)

finger After a transaction is committed , Its changes to the data in the database are persistent , Even if the database fails, it should not have any impact .

 

3、 ... and 、 Problems caused by concurrent transactions

When multiple transactions run concurrently , Often operate the same data to complete their own tasks ( namely Multiple users operate on the same data ). If the necessary isolation mechanism is not adopted, concurrency problems will occur .
 

1. Dirty reading (Dirty read)

Dirty reading means Data in another uncommitted transaction is read during one transaction .

When a transaction is accessing data and modifying the data , And this modification Not yet committed to the database in , At this time, another transaction is also Access and use This data . Because this data is not submitted yet , So the data read by another transaction is “ Dirty data ”, basis “ Dirty data ” The operation may not be correct .

2. Modification lost (Lost to modify)

finger Two transactions T1 and T2 Read the same data and modify ,T2 The submitted results cover T1 Results submitted , Lead to T1 The modification of is lost .
When a transaction reads a data , Another transaction also accesses the data , If this data is modified in the first transaction , The second transaction also modifies the data , Then the modification results in the first transaction will be lost , Therefore, it is called modification loss .

for example :
Business T1 Read data from a table A=20, Business T2 Also read A=20, Business T1 modify A=A-1, Business T2 Also modify A=A-1, final result A=19, Business T1 The modification of is lost .

3. It can't be read repeatedly (Unrepeatableread)

finger In a business , Read the same data multiple times , And before this business is over , Another transaction also accesses the data . that , Between two reads in the first transaction , Due to the modification of the second transaction, the data read by the first transaction twice may be different . That's what happened The data read twice in a transaction is different , So it's called unrepeatable reading .

for example :
Business T1 When reading a data , Business T2 The data was immediately modified and submitted to the database , Business T1 When you read the data again, you get different results , Non repeatable reading occurred .

4. Fantasy reading (Phantom read)

Unreal reading is also called virtual reading .
A business T1 Read a few lines of data , Then another concurrent transaction T2 Inserted some data , When a transaction T1 When you query again, you will find There are more records that didn't exist ( By business T2 Inserted records ), It's like an illusion , So it's called Unreal reading .

Non repeatable and dirty reads 、 The difference between fantasy reading

The difference between unrepeatable reading and dirty reading

Dirty reading It is a transaction that reads the uncommitted dirty data of another transaction ;
It can't be read repeatedly The data submitted by the previous transaction is read .

The difference between nonrepeatable reading and unreal reading

Both phantom and unrepeatable reads read another committed transaction ( This is where the dirty reading is different ), The difference is The same data item cannot be read and queried repeatedly , and Unreal reading is aimed at a batch of data as a whole ( Like the number of Numbers ).
 
It can't be read repeatedly The key point is to modify, for example, reading a record many times and finding that the values of some columns have been modified ;
Fantasy reading The key point is to add or delete. For example, you can read a record many times and find that the number of records increases or decreases .

 

Four 、 The isolation level of the transaction

4.1 SQL The standard defines four isolation levels

  1. READ-UNCOMMITTED( Read uncommitted data )

    Lowest isolation level , Allow read of uncommitted data changes
    Avoid losing changes , Can cause dirty reading 、 Phantom or unrepeatable reading .

    If a transaction has started to write data , Another transaction is not allowed to write at the same time , But allow other transactions to read this row of data .
    The isolation level can be “ Exclusive write lock ” Realization .

  2. READ-COMMITTED( Read submitted data )

    Allow to read data submitted by concurrent transactions
    Can prevent dirty reading , however Unreal reading or unrepeatable reading can still happen .

    The transaction reading data allows other transactions to continue to access the row data , But uncommitted write transactions will prevent other transactions from accessing the row .

  3. REPEATABLE-READ( Repeatable )

    Multiple reads of the same field are consistent , Unless the data is modified by the transaction itself
    Can prevent dirty and unrepeatable read , But phantom reading can still happen .

    This isolation level can be achieved by “ Shared read lock ” and “ Exclusive write lock ” Realization .

    MySQL Default isolation level yes Repeatable .

  4. SERIALIZABLE( Serializable )

    Highest isolation level , Completely obey ACID Isolation level . All transactions are executed one by one , In this way, there is no interference between transactions , But the cost is the highest , Lowest performance .
    It can prevent dirty reading 、 Unrepeatable reading and phantom reading .

    Provide strict transaction isolation . It requires the serialization of transactions , Transactions can only be executed one after another , But it can't be executed concurrently .
    If only by “ Row-level locks ” There is no way to serialize transactions , Other mechanisms must be used to ensure that the newly inserted data will not be accessed by the transaction just executing the query operation .

4.2 Transaction problems that can be solved by the isolation level

Isolation level Modification lost Dirty reading It can't be read repeatedly Fantasy reading
READ-UNCOMMITTED can xxx
READ-COMMITTED can can xx
REPEATABLE-READ can can can x
SERIALIZABLE can can can can

Higher isolation level , The more data integrity and consistency can be guaranteed , But the greater the impact on concurrent performance . For most applications , Priority can be given to setting the isolation level of the database system to Read Committed. It avoids dirty reads , And it has better concurrent performance . Although it can lead to non repeatable reading 、 Unreal reading and the second kind of missing update , In individual situations where such problems may occur , Can be controlled by an application using pessimistic or optimistic locks .

The default level for most databases is Read committed Read committed, such as Sql Server , Oracle.
MySQL The default level is Repeatable Repeatable-Read.

 
What needs to be noted here is

    And SQL The difference in standards is InnoDB Storage engine in REPEATABLE-READ( Repeatable ) The transaction isolation level uses Next-Key Lock Lock algorithm , So we can avoid the production of unreal reading , It works with other database systems ( Such as SQL Server) Is different . So InnoDB The default isolation level supported by the storage engine is REPEATABLE-READ( Repeatable ) The transaction isolation requirements can be fully guaranteed , That is to say SQL The standard SERIALIZABLE( Serializable ) Isolation level .
    Because the lower the isolation level , The fewer locks the transaction requests , So the isolation level of most database systems is READ-COMMITTED( Read submissions ) , But what you need to know is InnoDB The storage engine uses... By default REPEATABLE-READ( Repeatable ) There will be no loss of performance .

InnoDB Storage engine in Distributed transactions In general, we use SERIALIZABLE( Serializable ) Isolation level .

4.3 MySQL And Viewing and modifying isolation levels

  1. adopt SELECT @@tx_isolation; Order to see

    mysql> SELECT @@tx_isolation;
    +-----------------+
    | @@tx_isolation  |
    +-----------------+
    | REPEATABLE-READ |
    +-----------------+
    
  2. Set isolation level

    set  [glogal | session]  transaction isolation level  Isolation level name ;
    set tx_isolation=’ Isolation level name ;set transaction isolation level repeatable read;
    set tx_isolation=repeatable-read

    Set the isolation level of the database before starting the transaction !

    Use JDBC Set the isolation level for database transactions :

    Calling Connection Object's setAutoCommit(false) Before method . call Connection Object's setTransactionIsolation(level) You can set the isolation level of the current link , As for parameters level, have access to Connection Object field :
     Insert picture description here

    The code is as follows :

    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    
    try{
          
    	conn = JdbcUtils.getConnection();
    	// Set the isolation level of the link 
    	conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    	conn.setAutoCommit(false);	// Open transaction 
    }
    

    The setting of isolation level is only valid for the current link . For the use of MySQL For the command window , A window is a link , The isolation level set by the current window is only valid for transactions in the current window ; about JDBC For operating a database , One Connection Object is equivalent to a link , And for Connection The isolation level set by the object is only applicable to this object Connection Effective object , Link with other Connection The object has nothing to do with .

 

5、 ... and 、 The creation of transactions

  • Implicit transaction : The transaction has no obvious opening and closing marks
  • Explicit transaction : A transaction has distinct open and end tags Premise : Auto submit must be disabled first
 step 1: Open transaction 
    set autocommit=0;
    start transaction;  Optional , Open a transaction explicitly .
 step 2: Write... In a transaction sql sentence (select insert update delete)
       sentence 1
       sentence 2
 step 3: End the business 
    commit;  Commit transaction , And make all changes that have been made to the database permanent .
    rollback;  Rolling back ends the user's transaction , And undo all pending changes .

 

6、 ... and 、 The propagation characteristics of transactions

  1. PROPAGATION_REQUIRED: Default transaction type , without , Just create a new transaction ; If there is , Join the current transaction . For the vast majority of cases .

  2. PROPAGATION_REQUIRES_NEW: without , Just create a new transaction ; If there is , Just suspend the current transaction .

  3. PROPAGATION_NESTED: without , Just create a new transaction ; If there is , Just nest other transactions in the current transaction .

  4. PROPAGATION_SUPPORTS: without , Just in a non transactional way ; If there is , Use the current transaction .

  5. PROPAGATION_NOT_SUPPORTED: without , Just in a non transactional way ; If there is , Just suspend the current transaction . That is, transactions are not supported in any way .

  6. PROPAGATION_NEVER: without , Just in a non transactional way ; If there is , Throw an exception .

  7. PROPAGATION_MANDATORY: without , Throw an exception ; If there is , Use the current transaction .

 

7、 ... and 、 Lock mechanism of database

7.1 By lock type , Can be divided into shared locks 、 Exclusive lock

Shared lock (Share Locks, It's also called read lock 、S lock )

Multiple transactions can block a shared page ;
No transaction can modify the page ;
Usually the page is read ,S The lock is released immediately .
In execution select Statement needs to be given to the operation object ( Tables or records ) Add shared lock , However, it is necessary to check whether there is an exclusive lock before locking , without , You can add a shared lock ( An object can be added with n Shared locks ), Otherwise, it won't work .
Release of shared lock Usually after execution select After statement , Of course, it may be at the end of the transaction ( Including normal end and abnormal end ) When he was released , It mainly depends on the transaction isolation level set by the database .
 
Other users can read data concurrently , But no transaction can acquire an exclusive lock on the data , Until all shared locks have been released .
If business T For data objects A add S lock , The transaction T Only read A; Other affairs can only be right again A Add S lock , Instead of X lock , until T Release A Upper S lock . This ensures that other transactions can be read A, But in T Release A Upper S You can't do it before you lock it A Make any changes .

Exclusive lock (Exclusive Lock, Also called write locks 、X lock )

Only one transaction is allowed to block this page ;
Any other business has to wait until X Only when the lock is released can the lock page be accessed ;
X The lock cannot be released until the end of the transaction .
perform insert、update、delete Statement, you need to add an exclusive lock to the operated object , Before adding an exclusive lock, you must make sure that there are no other locks on the object , Once the exclusive lock is added , You can't lock this object any more .
Release of exclusive lock Usually at the end of a transaction ( There are exceptions , The transaction isolation level of the database is set to Read Uncommitted( Read uncommitted data ) When , In this case, the exclusive lock will be released after the update operation , Not at the end of the transaction ).
 
If business T For data objects A add X lock , Only T Read and modify A, Nothing else can be done to A Add any type of lock , until T Release A The lock on the . It prevents any other transaction from acquiring a lock on the resource , Until the original lock on the resource is released at the end of the transaction . In the update operation (INSERT、UPDATE or DELETE) Always apply an exclusive lock in the process .

The difference between the two

Shared lock : If the transaction T Data pair A After adding the shared lock , Then other affairs can only be for A Add shared lock , No Can you add an exclusive lock . Transactions that acquire shared locks can only read data , Can't modify data .

Exclusive lock : If the transaction T Data pair A With the lock on , Then nothing else can be right A Add any kind of blockade . Transactions that acquire exclusive locks can read data , It can also modify data .

7.2 According to the granularity of lock , It can be divided into table level locks 、 Row-level locks 、 Page level lock

Table lock

Lock the whole table directly , During locking , Other processes cannot write to the table . If you are writing a lock , Other processes are not allowed to read .
Characteristic is : Low overhead 、 Locked fast , A deadlock will not occur . Maximum locking granularity , The highest probability of lock collisions , Lowest degree of concurrency .
 
MYISAM The storage engine uses table level locks .

Row-level locks

Lock only the specified records , In this way, other processes can still operate on other records in the same table .
characteristic : Spending big , Lock the slow , A deadlock occurs . The granularity of locking is the smallest , The lowest probability of lock collisions , The highest degree of concurrency .
 
InnoDB The storage engine supports both row level locks , Table level locks are also supported , But the default is row level locking .

Page level lock

Lock an adjacent set of records at a time . The cost and locking time are between table level lock and row level lock ; A deadlock occurs ; Locking granularity is also between table level lock and row level lock , The concurrency is average .

7.3 Divided by use mechanism , It can be divided into optimistic lock 、 Pessimistic locking

Pessimistic locking (Pessimistic Lock)

When you want to modify a piece of data in the database , To avoid being modified by others at the same time , The best way is to lock the data directly to prevent concurrency . With the help of database lock mechanism , Lock before modifying data , The way to modify it is called pessimistic concurrency control 【Pessimistic Concurrency Control, abbreviation “PCC”, also called “ Pessimistic locking ”】
 
Pessimistic locking , With strong exclusivity and exclusivity . It refers to the data being exposed to the outside world ( Includes other current transactions of the system , And transactions from external systems ) The revision was conservative . therefore , In the whole data processing process , Lock the data . Pessimistic lock implementation , It often relies on the locking mechanism provided by the database ( Only the locking mechanism provided by the database layer can truly guarantee the exclusivity of data access , otherwise , Even in this system to implement the locking mechanism , There is no guarantee that external systems will not modify the data ).

Optimism lock (Optimistic Lock)

Optimistic lock is relative to pessimistic lock , Optimistic locking assumes that data generally does not cause conflict , So when the data is submitted for update , The data conflict will be formally detected or not , If conflict , The exception information is returned to the user , Let the user decide how to do it . Optimistic lock is suitable for reading more and writing less , This can improve the throughput of the program .

 


I like it with the support of one button three times !
If there are mistakes, please point out ~
Reprint please indicate :
https://blog.csdn.net/vihem/article/details/120983965

原网站

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