Understand MySQL transactions in one article: Improve your database operation skills

Insert image description here

Overview

Transactions can guarantee the atomicity of multiple operations, either all succeed or all fail. For databases, transactions guarantee that batches of DML will either succeed or fail. Transactions have four characteristics ACID

Atomicity _ _

All operations in the entire transaction must be completed as a unit (or all canceled).

Consistency

The database remains in a consistent state before and after a transaction begins.

Isolation

One transaction does not affect the operation of other transactions.

Durability

After the transaction is completed, the changes made to the database by the transaction will be persisted in the database and will not be rolled back.

There are some concepts in transactions:

  • Transaction: a batch of operations (a set of DML)
  • Start Transaction
  • Rollback transaction (rollback)
  • Commit transaction
  • SET AUTOCOMMIT: Disable or enable automatic commit mode for transactions

When a DML statement is executed, a transaction is actually started.

Note about transaction rollback: only insert, delete, and update statements can be rolled back, select cannot be rolled back (rolling back select has no meaning), and create, drop, and alter cannot be rolled back.

Transactions only have effect on DML.

Note: The transaction ends after rollback or commit.

Transaction commit and rollback demonstration

1. Create table


mysql> create table user(
    -> id int(11) primary key not null auto_increment,
    -> username varchar(30),
    -> password varchar(30)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.13 sec)

2. Query the data in the table

mysql> select * from user;
Empty set

3. Open the transaction

mysql> START TRANSACTION;
Query OK, 0 rows affected (0.15 sec)

4. Insert data

mysql> insert into user(username,password) values('zhangsan','123');
Query OK, 1 row affected (0.19 sec)

5. View data

mysql> select * from user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | zhangsan | 123      |
+----+----------+----------+
1 row in set (0.32 sec)

6. Modify data and view the modified data

mysql> update user set username='lisi' where id=1;
Query OK, 1 row affected (0.26 sec)
Rows matched: 1  Changed: 1  Warnings: 0
mysql> select * from user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | lisi     | 123      |
+----+----------+----------+
1 row in set (0.35 sec)

7. Roll back the transaction and view the user table

mysql> rollback;
Query OK, 0 rows affected (0.26 sec)

mysql> select * from user;
Empty set

Autocommit mode

Autocommit mode is used to determine how and when new transactions are started.

Enable autocommit mode:

  • If autocommit mode is enabled, a single DML statement will start a new transaction by default.
  • If the statement is executed successfully, the transaction will be automatically committed and the execution results of the statement will be saved permanently.
  • If execution of a statement fails, the transaction is automatically rolled back and the results of the statement are cancelled.
  • In autocommit mode, you can still use the START TRANSACTION statement to explicitly start a transaction. At this time, a transaction can still contain multiple statements until these statements are uniformly committed or rolled back.

Disable autocommit mode:

  • If autocommit is disabled, transactions can span multiple statements.
  • In this case, the transaction can be explicitly committed or rolled back using the COMMIT and ROLLBACK statements.

Autocommit mode can be controlled through the server variable AUTOCOMMIT.

For example:

mysql> SET AUTOCOMMIT = OFF; 
mysql> SET AUTOCOMMIT = ON;
或
mysql> SET SESSION AUTOCOMMIT = OFF;
mysql> SET SESSION AUTOCOMMIT = ON;
show variables like '%auto%'; -- 查看变量状态

transaction isolation level

isolation level

A transaction's isolation level determines the level of visibility between transactions.

When multiple clients access the same table concurrently, the following consistency issues may occur:

  • Dirty Read _

A transaction begins to read a certain row of data, but another transaction has updated the data but failed to submit it in time, which results in a dirty read.

  • Non- repeatable Read

In the same transaction, the same read operation produces different results when reading the same data twice. This is a non-repeatable read.

  • Phantom Read _

A phantom read is a row that did not exist before in the same transaction and a new row that appears due to the commit of other transactions.

Four isolation levels

InnoDB implements four isolation levels to control modifications made by transactions and notify modifications to other concurrent transactions:

Read uncommitted (READ UMCOMMITTED)

Allows one transaction to see uncommitted modifications of other transactions.

READ COMMITTED

A transaction is allowed to only see modifications that have been committed by other transactions, and uncommitted modifications are invisible.

REPEATABLE READ

Ensure that if you execute the same SELECT statement twice in a transaction, you will get the same results, regardless of whether other transactions commit these changes. (Bank General Ledger) This isolation level is the default setting of InnoDB.

Serialization (SERIALIZABLE) [Serialization]

Completely isolate one transaction from other transactions.

Example: A can open things, and B can also open things

When A executed the DML statement in the transaction, it was not submitted.

B cannot execute DML or DQL statements

The relationship between isolation levels and consistency issues

isolation level dirty read non-repeatable read phantom reading
Read uncommitted possible possible possible
Read submitted impossible possible possible
repeatable read impossible impossible Not possible with InnoDB
serialization impossible impossible impossible

Set the server default isolation level

By modifying configuration file settings

You can my.iniuse transaction-isolationoptions in the file to set the server's default transaction isolation level

This option value can be:

  • READ-UNCOMMITTED
  • READ-COMMITTED
  • REPEATABLE-READ
  • SERIALIZABLE

For example:

[mysqld]

transaction-isolation = READ-COMMITTED

Dynamically set the isolation level through commands

The isolation level can also be set dynamically in the running server using the SET TRANSACTION ISOLATION LEVEL statement.

Its syntax pattern is:

SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL <isolation-level>

Which can be:

  • READ-UNCOMMITTED
  • READ-COMMITTED
  • REPEATABLE-READ
  • SERIALIZABLE

For example:SET TRANSACTION ISOLATION LEVEL **REPEATABLE READ**;

Isolation level scope

The scope of transaction isolation level is divided into two types:

  • Global level: valid for all sessions
  • Session level: only valid for the current session

For example, set the session-level isolation level to READ COMMITTED

mysql> SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
或:
mysql> SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

Set the global isolation level to READ COMMITTED:

mysql> SET GLOBAL TRANSACTION ISOLATION LEVEL READ COMMITTED;

Check the isolation level

The server variable tx_isolation (including session-level and global-level variables) stores the current session isolation level.

To view the current isolation level, access the tx_isolation variable:

View the current isolation level at the session level:

mysql> SELECT @@tx_isolation;
    或: 
mysql> SELECT @@session.tx_isolation;
//查看全局级的当前隔离级别: 
mysql> SELECT @@global.tx_isolation;

Concurrent transactions and isolation level examples

read uncommitted (uncommitted read) --dirty read (Drity Read):

Conversation 1 Conversation 2
mysql> prompt s1> mysql> use bjpowernode
s1>use bjpowernode mysql> prompt s2>
s1>create table tx (id int(11),num int (10));
s1>set global transaction isolation level read uncommitted;
s1>start transaction;
s2>start transaction;
s1>insert into tx values (1,10);
s2>select * from tx;
s1>rollback;
s2>select * from tx;

read committed(read committed)

Conversation 1 Conversation 2
s1> set global transaction isolation level read committed;
s1>start transaction;
s2>start transaction;
s1>insert into tx values (1,10);
s1>select * from tx;
s2>select * from tx;
s1>commit;
s2>select * from tx;

repeatable read(repeatable read)

Conversation 1 Conversation 2
s1> set global transaction isolation level repeatable read;
s1>start transaction; s2>start transaction;
s1>select * from tx;
s1>insert into tx values (1,10);
s2>select * from tx;
s1>commit;
s2>select * from tx;

Guess you like

Origin blog.csdn.net/sinat_28521487/article/details/132869613