MySQL Advanced Chapter - Overview and Simple Application of Transactions

Article directory:

1. Transaction overview

2. ACID characteristics of transactions

3. How to use transactions?

3.1 Explicit transactions

3.2 Implicit Transactions

4. Practical case


1. Transaction overview

First, we can look at the support of various storage engines for transactions. Only INNODB supports transactions.

Transaction: A set of logical operation units that cause data to change from one state to another.
The principle of transaction processing: ensure that all transactions are executed as a unit of work, even if a failure occurs, this execution method cannot be changed. When multiple operations are performed in a transaction, either all transactions are committed ( commit ) , then these changes are permanently saved; or the database management system will discard all changes made , and the entire transaction is rolled back ( rollback ) to initial state.

2. ACID characteristics of transactions

Atomicity (  atomicity ): Atomicity means that a transaction is an indivisible unit of work, either all committed or all failed and rolled back.
Consistency (  consistency ): (The description of consistency on many domestic websites is wrong. For details, you can refer to Wikipedia 's description of Consistency .) By definition, consistency refers to the transformation of data from one legality state to another before and after transaction execution legal status . This state is semantic rather than syntactic, and is related to specific business. So what is the legal data state? A state that satisfies the predetermined constraints is called a valid state. In layman's terms, this state is defined by you (such as satisfying real-world constraints). If this state is satisfied, the data is consistent; if this state is not satisfied, the data will be
is inconsistent! If an operation in the transaction fails, the system will automatically undo the currently executing transaction and return to the state before the transaction operation.
Isolation  : The isolation of a transaction means that the execution of a transaction cannot be interfered by other transactions , that is, the operations and data used within a transaction are isolated from other concurrent transactions , and concurrently executed transactions cannot interact with each other. interference.
Durability  : Durability means that once a transaction is committed, its changes to the data in the database are permanent , and subsequent operations and database failures should not have any effect on it.
Durability is guaranteed through the transaction log. Logs include redo logs and rollback logs . When we modify the data through a transaction, the change information of the database is first recorded in the redo log, and then the corresponding row in the database is modified. The advantage of this is that even if the database system crashes, the redo logs that have not been updated to the database system can be found and re-executed after the database is restarted, thereby making the transaction durable.

3. How to use transactions?

There are two ways to use transactions, namely explicit transactions and implicit transactions .

3.1 Explicit transactions

Step 1 : START TRANSACTION or BEGIN , the function is to explicitly start a transaction.
The START TRANSACTION statement is different from BEGIN in that it can be followed by several modifiers :
READ ONLY : Indicates that the current transaction is a read-only transaction , that is, the database operations belonging to this transaction can only read data, but cannot modify data.
READ WRITE : Indicates that the current transaction is a read- write transaction , that is, the database operation belonging to the transaction can either read data or modify data.
WITH CONSISTENT SNAPSHOT : Start consistent read.
Step 2 : Operations in a series of transactions (mostly DML , no DDL )
Step 3 : Commit the transaction or abort the transaction (i.e. roll back the transaction)
mysql> BEGIN; 
#或者 
mysql> START TRANSACTION;

# 提交事务。当提交事务后,对数据库的修改是永久性的。 
mysql> COMMIT; 

# 回滚事务。即撤销正在进行的所有没有提交的修改 
mysql> ROLLBACK; 

# 将事务回滚到某个保存点。 
mysql> ROLLBACK TO [SAVEPOINT]

3.2 Implicit Transactions

There is a system variable autocommit in MySQL : (indicates that transactions are automatically committed by default)

Of course, if we want to turn off this auto- commit feature, we can use one of the following two methods:
Explicitly use the START TRANSACTION or BEGIN statement to start a transaction. In this way, the auto-commit function will be temporarily turned off before the transaction is committed or rolled back.
Set the value of the system variable autocommit to OFF , like this:
SET autocommit = OFF; 
#或
SET autocommit = 0;
#set autocommit = false;

SHOW VARIABLES LIKE 'autocommit';#默认是ON

UPDATE account SET balance = balance - 10 WHERE id = 1; #此时这条DML操作是一个独立的事务

UPDATE account SET balance = balance + 10 WHERE id = 2; #此时这条DML操作是一个独立的事务
SET autocommit = FALSE; #针对于DML操作是有效的,对DDL操作是无效的。

UPDATE account SET balance = balance - 10 WHERE id = 1;

UPDATE account SET balance = balance + 10 WHERE id = 2; 

COMMIT; #或rollback;  此时以上两个UPDATE为一个事务整体
#我们在autocommit为true的情况下,使用start transaction 或begin开启事务,那么DML操作就不会自动提交数据

START TRANSACTION;

UPDATE account SET balance = balance - 10 WHERE id = 1;

UPDATE account SET balance = balance + 10 WHERE id = 2; 

COMMIT; #或rollback;

Of course, in mysql, there are also some cases where data is implicitly submitted:

Data definition language ( Data definition language , abbreviated as: DDL )
Implicitly use or modify tables in mysql database
transaction control or statement about locking
① When we use the START TRANSACTION or BEGIN statement to start another transaction before a transaction has been committed or rolled back, the previous transaction will be implicitly committed. which is:
② The current value of the autocommit system variable is OFF . When we manually turn it ON , the transaction to which the preceding statement belongs will also be implicitly committed.
③ Using LOCK TABLES , UNLOCK TABLES and other locking statements will also implicitly commit the transaction to which the previous statement belongs.

4. Practical case

USE atguigudb2;

CREATE TABLE user(
		NAME VARCHAR(15) PRIMARY KEY
);

SELECT * FROM user;

Next, we start a transaction, insert a piece of data into the table, and then commit. 

BEGIN;
INSERT INTO user VALUES('张三');
COMMIT;

SELECT * FROM user;

Open another transaction and add two pieces of data to the table. The second INSERT will report an error. At this time, when the transaction is submitted, only the first INSERT will succeed. 

BEGIN;
INSERT INTO user VALUES('李四');
INSERT INTO user VALUES('李四');
COMMIT;

SELECT * FROM user;

Next, we will empty the table and use ROLLBACK to roll back for practice.

TRUNCATE TABLE user;

SELECT * FROM user;

BEGIN;
INSERT INTO user VALUES('张三');
COMMIT;

SELECT * FROM user;

The following is the same as the above operation, we insert two pieces of the same data into the table, and the second INSERT will report an error.

Execute ROLLBACK to see how the data in the database table is?

INSERT INTO user VALUES('李四'); #ROLLBACK回滚到此处
INSERT INTO user VALUES('李四');

ROLLBACK;
SELECT * FROM user;

Next, clear the data in the table and do a new operation. Modify the value of the completion_type variable to 1.

TRUNCATE TABLE user;
SELECT * FROM user;

SELECT @@completion_type;
SET @@completion_type = 1;
SELECT @@completion_type;

BEGIN;
INSERT INTO user VALUES('张三'); 
COMMIT; #ROLLBACK回滚到此处

SELECT * FROM user;

INSERT INTO user VALUES('李四');
INSERT INTO user VALUES('李四'); 

ROLLBACK;
SELECT * FROM user;

 

The following demonstrates the case of INNODB and MYISAM in the context of transactions.

CREATE TABLE test1(i INT) ENGINE = INNODB;
CREATE TABLE test2(i INT) ENGINE = MYISAM;

#针对于innodb表
BEGIN;
INSERT INTO test1 VALUES (1);

SELECT * FROM test1;

It can be seen that the storage engine is an INNODB table. After ROLLBACK, it will normally roll back to the state at the beginning of the transaction, that is, there is no data in the table after the rollback. 

ROLLBACK;
SELECT * FROM test1;

#针对于myisam表:不支持事务
BEGIN;
INSERT INTO test2 VALUES (1);

SELECT * FROM test2;

It can be seen that the storage engine is a MYISAM table. After ROLLBACK, the data inserted in the table still exists, that is, the MYISAM storage engine does not support transactions.

ROLLBACK;
SELECT * FROM test2;

The following is an example for SAVEPOINT.

#举例3:体会savepoint
CREATE TABLE user3(
		NAME VARCHAR(15),
		balance DECIMAL(10,2)
);

BEGIN;
INSERT INTO user3(NAME,balance) VALUES('张三',1000);
COMMIT;

SELECT * FROM user3;

BEGIN;
UPDATE user3 SET balance = balance - 100 WHERE NAME = '张三'; # 900
UPDATE user3 SET balance = balance - 100 WHERE NAME = '张三'; # 800

SAVEPOINT s1;#设置保存点

UPDATE user3 SET balance = balance + 1 WHERE NAME = '张三'; # 801

ROLLBACK TO s1; #回滚到保存点

SELECT * FROM user3;

At this time, ROLLBACK TO s1 is normally rolled back to the position of savepoint s1, and the balance is 800. 

The following is to roll back the entire transaction, and then go back to the time when the data balance was initially added to 1000. 

ROLLBACK; #回滚操作

SELECT * FROM user3;

Guess you like

Origin blog.csdn.net/weixin_43823808/article/details/124322118