MySQL database--transaction

foreword

MySQL transactions are mainly used to process data with a large amount of operations and high complexity. For example, in the personnel management system, if you want to delete a person, you need to delete the basic information of the person, and you need to delete the information related to the person, such as mailboxes, articles, and so on. In this way, these database operation statements constitute a transaction!


1. The concept of things

  • A transaction is a mechanism, an operation sequence, which includes a set of database operation commands, and submits or revokes operation requests to the system together with all the commands as a whole, that is, this set of database commands is either executed or not executed.

  • A transaction is an indivisible logical unit of work. When performing concurrent operations on a database system, a transaction is the smallest control unit.

  • Transactions are suitable for scenarios where multiple users operate database systems at the same time, such as banks, insurance companies, and securities trading systems.

  • Transactions ensure data consistency through the integrity of transactions.

To put it bluntly, the so-called transaction is a sequence of operations. These operations are either executed or not executed. It is an indivisible unit of work.

Second, the ACID characteristics of the transaction

ACID refers to the four characteristics that transactions should have in a reliable database management system (DBMS): Atomicity, Consistency, Isolation, and Durability. These are a few properties that a reliable database should have.

  1. Atomicity:
  • It means that a transaction is an indivisible unit of work, and the operations in the transaction either all occur or none occur.

  • A transaction is a complete operation, and the elements of a transaction are inseparable.

  • All elements in a transaction must be committed or rolled back as a whole.

  • If any element in the transaction fails, the entire transaction fails.

  • Case:
    When A transfers 100 yuan to B, he only executes the deduction statement and submits it. If there is a sudden power failure, A account has already been debited, but B account has not received the additional payment. cause disputes. In this case, the atomicity of the transaction is required to ensure that the transaction is either executed or not executed.

  1. consistency:
  • It means that the integrity constraints of the database are not violated before the transaction starts and after the transaction ends.

  • When the transaction completes, the data must be in a consistent state.

  • Before a transaction starts, the data stored in the database is in a consistent state.

  • During an ongoing transaction, data may be in an inconsistent state.

  • When the transaction completes successfully, the data must come back to a known consistent state again.

  • Case:
    For bank transfer transactions, regardless of whether the transaction succeeds or fails, it should be ensured that the total deposits of A and B in the table after the transaction is completed are consistent with those before the transaction is executed.

  1. Isolation:
  • It means that in a concurrent environment, when different transactions manipulate the same data at the same time, each transaction has its own complete data space.

  • All concurrent transactions that modify data are isolated from each other, indicating that a transaction must be independent, it should not depend on or affect other transactions in any way.
    A transaction that modifies data can access the data before another transaction using the same data begins, or after another transaction using the same data ends.

The execution of a transaction cannot be interfered with by other transactions

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

  • It means that regardless of whether the system fails or not, the results of transaction processing are permanent.
    Once a transaction is committed, the effects of the transaction are permanently retained in the database.

  1. There are several types of interaction between transactions, which are
  • Dirty read (read uncommitted data):
    Dirty read refers to reading uncommitted data of other transactions. Uncommitted means that these data may be rolled back, that is, they may not be stored in the database in the end, that is, they do not exist The data. The data that has been read and must eventually exist is a dirty read

    • In case 1
      , for example, transaction B modified data X during execution. Before committing, transaction A read X, but transaction B rolled back, so transaction A formed a dirty read. That is to say, the data read by the current transaction is the data that other transactions want to modify but have not successfully modified.
  • Non-repeatable read (multiple reads before and after, the data content is inconsistent):
    two identical queries within a transaction return different data. This is caused by the commits modified by other transactions in the system at the time of the query.

    • Case:
      Transaction A obtains a row of record row1 in the first query, and after transaction B submits the modification, transaction A obtains row1 in the second query, but the column content has changed.
select * from member;
1 zhangsan  20分
select * from Member;
1 zhangsan  30分

  • Phantom reading (multiple reads before and after, the total amount of data is inconsistent):
    a transaction modifies the data in a table, and this modification involves all the data rows in the table. At the same time, another transaction also modifies the data in this table. This modification is to insert a new row of data into the table. Then, the user who operated the previous transaction will find that there are still unmodified data rows in the table, as if an illusion has occurred.

    • The case column
      assumes that transaction A has changed the content of some rows, but has not yet committed it. At this time, transaction B inserts the same record row as the record before transaction A changed, and it is committed before transaction A commits, and this When querying in transaction A, you will find that the change just now has no effect on some data, but in fact it was just inserted by transaction B, which makes the user feel magical and hallucinating. This is called phantom read select
      * from member;
      6 records were found
alter table member change

select * from member;
查询到了10条记录 (更新了6条数据,还有4条数据,我没有更新到)

  • Lost update:
    Two transactions read the same record at the same time. A modifies the record first, and B also modifies the record (B does not know that A has modified it). After B submits the data, the modification result of B overwrites the modification result of A.
    • Case
      A 30 -> 40 Transaction
      B is completed first 30 -> 50 The
      transaction result of B will overwrite the transaction result of A, and the final value is 50

3. Mysql and transaction isolation level (four types)

  1. read uncommitted (read uncommitted):
  • Read uncommitted data: do not resolve dirty reads
  • Dirty reads are allowed. As long as other transactions modify the data, even if they are not committed, this transaction can still see the modified data value. That is, it is possible to read data modified by uncommitted transactions in other sessions.
  1. read committed (submit read):
  • Read committed data: dirty reads can be resolved
  • Only submitted data can be read. Most databases such as Oracle default to this level (non-repeatable read).
  1. repeatable read (repeatability):
  • Re-reading: Can solve dirty reads and non-repeatable reads—mysql default
  • Repeatable reading. Regardless of whether other transactions have modified and committed data, the data values ​​seen in this transaction are always unaffected by other transactions
  1. serializable: Serializable:
  • It can solve dirty reads, non-repeatable reads and virtual reads—equivalent to lock tables
    —fully serialized reads. Each read needs to obtain a table-level shared lock, and reads and writes will block each other.

MySQL's default transaction level is repeatable read, while Oracle and SQL Server are read committed.

  1. Scope of transaction isolation level (2 types)
  • Global level: valid for all sessions (the global configuration will be loaded into the session level in the database, and the global configuration will take effect after restarting)

  • Session level: only valid for the current session (effective immediately)

  • Query the global transaction isolation level

set global transaction isolation level read committed;
#例:
mysql> set global transaction isolation level read committed;
Query OK, 0 rows affected (0.00 sec)

mysql> show global variables like '%isolation%';	
+---------------+----------------+
| Variable_name | Value          |
+---------------+----------------+
| tx_isolation  | READ-COMMITTED |		//已经改为提交读
+---------------+----------------+
1 row in set (0.00 sec)


  • Set session transaction isolation level
set session transaction isolation level read committed;
#例:
mysql> set session transaction isolation level read committed;
Query OK, 0 rows affected (0.00 sec)

mysql> show session variables like '%isolation%';
+---------------+----------------+
| Variable_name | Value          |
+---------------+----------------+
| tx_isolation  | READ-COMMITTED |		//查看已经更改为提交读
+---------------+----------------+
1 row in set (0.00 sec)



4. Transaction control statement

BEGIN 或 START TRANSACTION:显式地开启一个事务。

COMMIT 或 COMMIT WORK:提交事务,并使已对数据库进行的所有修改变为永久性的。

ROLLBACK 或 ROLLBACK WORK:回滚会结束用户的事务,并撤销正在进行的所有未提交的修改。

SAVEPOINT S1:使用 SAVEPOINT 允许在事务中创建一个回滚点,一个事务中可以有多个 SAVEPOINT;“S1”代表回滚点名称。

ROLLBACK TO [SAVEPOINT] S1:把事务回滚到标记点。

  • template:
mysql> create database test;		//创建test库
Query OK, 1 row affected (0.00 sec)

mysql> use test;		//切换到test
Database changed

mysql> create table info(		//创建info表
    -> id int(10) primary key not null,
    -> name varchar(40),
    -> money double
    -> );
Query OK, 0 rows affected (0.15 sec)


mysql> insert into info values(1,'A',1000);		//添加数据
Query OK, 1 row affected (0.00 sec)

mysql> insert into info values(2,'B',1000);		//添加数据
Query OK, 1 row affected (0.00 sec)

mysql> select * from info;		//查询数据
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |  1000 |
|  2 | B    |  1000 |
+----+------+-------+
2 rows in set (0.00 sec

  1. test commit transaction
mysql> begin;		//开启事务
Query OK, 0 rows affected (0.00 sec)

mysql> update info set money= money - 100 where name='A';	//事务
select * from info;

mysql> commit;		//提交事务

###退出重进
quit
mysql -u root -p	
use SCHOOL;

mysql> select * from info;		//数据已经被更改
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |   900 |
|  2 | B    |  1000 |
+----+------+-------+
2 rows in set (0.00 sec)

  1. test rollback transaction
mysql> select * from info;
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |   900 |
|  2 | B    |  1000 |
+----+------+-------+
2 rows in set (0.00 sec)begin;

mysql> begin;		//开启事务
Query OK, 0 rows affected (0.00 sec)

mysql> update info set money= money + 100 where name='A';	//修改数据
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from info;	//查看
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |  1000 |
|  2 | B    |  1000 |
+----+------+-------+
2 rows in set (0.00 sec)

mysql> rollback;		//回滚
Query OK, 0 rows affected (0.00 sec)

####退出重进
mysql> quit
mysql -u root -p
mysql> use SCHOOL;
mysql> select * from info;	//再次查看,数据已经回滚
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |   900 |
|  2 | B    |  1000 |
+----+------+-------+
2 rows in set (0.00 sec)


  1. Test multi-point rollback
mysql> begin;		//开启事务

mysql> update info set money= money + 100 where name='A';	//修改更新数据

mysql> select * from info;	//查看数据
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |  1000 |
|  2 | B    |  1000 |
+----+------+-------+
2 rows in set (0.00 sec)

mysql> savepoint s1;		//创建回滚点s1 
Query OK, 0 rows affected (0.00 sec)

mysql> update info set money= money + 100 where name='B';	//修改更新数据

mysql> select * from info;
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |  1000 |
|  2 | B    |  1100 |
+----+------+-------+
2 rows in set (0.00 sec)

mysql> savepoint s2;	//创建回滚点s2
Query OK, 0 rows affected (0.00 sec)

mysql> insert into info values(3,'C',1000);		//插入新数据
Query OK, 1 row affected (0.00 sec)

mysql> select * from info;	
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |  1000 |
|  2 | B    |  1100 |
|  3 | C    |  1000 |
+----+------+-------+
3 rows in set (0.00 sec)

mysql> rollback to s1;		//回滚到s1
Query OK, 0 rows affected (0.00 sec)

mysql> select * from info;	//再次查看发现数据已经回滚
+----+------+-------+
| id | name | money |
+----+------+-------+
|  1 | A    |  1000 |
|  2 | B    |  1000 |
+----+------+-------+
2 rows in set (0.00 sec)


  1. Use set settings to control transactions
SET AUTOCOMMIT=0;						#禁止自动提交
SET AUTOCOMMIT=1;						#开启自动提交,Mysql默认为1
SHOW VARIABLES LIKE 'AUTOCOMMIT';		#查看Mysql中的AUTOCOMMIT值
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| autocommit    | ON    |
+---------------+-------+
1 row in set (0.00 sec)

如果没有开启自动提交,当前会话连接的mysql的所有操作都会当成一个事务直到你输入rollback|commit;当前事务才算结束。当前事务结束前新的mysql连接时无法读取到任何当前会话的操作结果。
如果开起了自动提交,mysql会把每个sql语句当成一个事务,然后自动的commit。
当然无论开启与否,begin; commit|rollback; 都是独立的事务。

use SCHOOL;
select * from info;
SET AUTOCOMMIT=0;		//禁止自动提交
SHOW VARIABLES LIKE 'AUTOCOMMIT';	//查看Mysql中的AUTOCOMMIT值
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| autocommit    | NO    |
+---------------+-------+
update info set money= money + 100 where name='B';
select * from info;
quit

mysql -u root -p
use SCHOOL;
select * from info;

Summarize

  • The ACID characteristics of things are: atomicity, consistency, isolation, and persistence

  • The interaction between transactions is divided into: dirty read, non-repeatable read, phantom read, lost update

  • The transaction isolation level is divided into: read uncommitted (uncommitted read), read committed (committed read), repeatable read (repeatable), serializable: serialization

  • The default transaction processing level of mysql is repeatable read

  • The scope of the transaction isolation level is divided into
    global level: valid for all sessions
    session level: valid only for the current session

Guess you like

Origin blog.csdn.net/weixin_60917414/article/details/131271560