This article takes you to an introduction to the affairs of MySQL

Preface:
Transaction ( Transaction) is an execution unit (Unit) composed of a set of SQL, and is the basic unit of database concurrency control and recovery rollback. A transaction may contain multiple SQLs, either all fail or all succeed. Today we will learn in detail.

1. The origin of the transaction

For most programmers, their task is to map real-world business scenarios to the database world. For example, a bank will create a table to store people's account information account:

mysql> CREATE TABLE account (
    id INT NOT NULL AUTO_INCREMENT COMMENT '自增id',
    name VARCHAR(100) COMMENT '客户名称',
    balance INT COMMENT '余额',
    PRIMARY KEY (id)
);
Query OK, 0 rows affected (0.04 sec)

Zhang San and Li Si are good friends. They both go to the bank to open an account, and the assets they own in the real world will be reflected in the account table in the database world. For example, now Zhang San has 11 yuan, and Li Si only has 2 yuan, so this situation in reality is mapped to the account table of the database like this:

mysql> INSERT INTO account(name,balance) VALUES ('张三',11),('李四',2);
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM account;
+----+--------+---------+
| id | name   | balance |
+----+--------+---------+
|  1 | 张三   |      11 |
|  2 | 李四   |       2 |
+----+--------+---------+
2 rows in set (0.00 sec)

At a specific moment, the assets owned by guys like Zhang San Li Si in the bank have a specific value, and these specific values ​​can also be described as a state of the account in the real world at this specific moment. As time goes by, Zhang San and Li Si may successively carry out operations such as depositing money in the account, withdrawing money, or transferring money to others, so that the balance in their accounts may change, and each operation is equivalent to an account in the real world. a state transition. As a mapping of the real world, the database world must of course undergo corresponding changes. I don’t know if I don’t change, I’m startled when I change, some seemingly simple state transitions in the real world are not so easy to map to the database world. For example, once Li Si needed 10 yuan, and he called Zhang San in a hurry to borrow 10 yuan. In the real world, Zhang San walked to the ATM, entered Li Si's account number and the transfer amount of 10 yuan, and then pressed Confirmed, Zhang San pulled out his card and left. For the database world, it is equivalent to executing the following two statements:

mysql> UPDATE account SET balance = balance - 10 WHERE id = 1;
Query OK, 1 row affected (0.03 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> UPDATE account SET balance = balance + 10 WHERE id = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

But there is a problem here. What should I do if the server suddenly loses power when only one of the above two statements is executed? Deducted Zhang San’s money, but did not transfer it to Li Si~ Even for a single statement, we have Buffer Poolsaid before when we nagged that when we read and write access to a certain page, we will first load this page into Buffer PoolIn the future, if a page is modified later, the modification will not be synchronized to the disk immediately, but only the modified page will be added to the Buffer Poollinked flushlist, and it will be refreshed to the disk at a later point in time. If the system crashes before the modified page is flushed to disk, isn't Li Si still out of money? Or in the process of refreshing the disk (only part of the data is refreshed to the disk) the system crashes and Li Si has no money?

How can we ensure that poor Li Si is rich? In fact, if we think about it carefully, we just want some database operations to conform to the rules of state transition in the real world. The uncles who design the database have carefully calculated and calculated. There are several rules for state transition in the real world. Let’s take it slowly. .

1.1 Atomicity

In the real world, the transfer operation is an inseparable operation, that is to say, either there is no transfer at all, or the transfer is successful, and there cannot be an intermediate state, that is, half of the transfer. When designing a database, this 要么全做,要么全不做kind of rule is called 原子性. However, an inseparable operation in the real world may correspond to several different operations in the database world, and an operation in the database may also be decomposed into several steps (such as modifying the cache page first, and then refreshing it to disk, etc.) , the most terrible thing is that unexpected errors may occur at any possible time (maybe an error in the database itself, or an error in the operating system, or even a direct power failure, etc.) and the operation cannot continue, so Li Four may also have money. In order to ensure the atomicity of certain operations in the database world, it is necessary to spend some effort when designing the database to ensure that if an error occurs during the execution of the operation, the operation that has been done will be restored to the state before it was executed. What we will talk about in detail in the following chapters.

1.2 Isolation

The two state transitions in the real world should not affect each other. For example, Zhang San and Li Si make two simultaneous transfers of 5 yuan (assuming that they can be operated on two ATMs at the same time). Then in the end Zhang San's account will definitely be 10 yuan less, and Li Si's account will definitely be 10 yuan more. But in the corresponding database world, things get a little more complicated. In order to simplify the problem, we roughly assume that the process of Zhang San transferring 5 yuan to Li Si consists of the following steps:

  • Step 1: Read the balance of Zhang San's account into variable A. This step is abbreviated asread(A)
  • Step 2: Subtract the transfer amount from the balance of Zhang San's account. This step is abbreviated asA = A - 5
  • Step 3: Write the modified balance of Zhang San's account to the disk. This step is abbreviated aswrite(A)
  • Step 4: Read the balance of Li Si's account to variable B, this step is abbreviated asread(B)
  • Step 5: Add the balance of Li Si's account to the transfer amount, this step is abbreviated asB = B + 5
  • Step 6: Write the modified balance of Li Si's account to the disk. This step is abbreviated aswrite(B)

We refer to the two simultaneous transfer operations from Zhang San to Li Si respectively as the T1sum T2. In the real world, T1the T2sum should have nothing to do with it. It can be executed first T1and then executed T2, or executed first T2and then executed T1. The corresponding database operation like this:

insert image description here
But unfortunately, the operations in the real database T1may T2be performed alternately, such as this:

insert image description here
If two transfers are performed according to the execution sequence in the above figure, there will be 6RMB remaining in Zhang San’s account in the end, which is equivalent to only deducting 5RMB, but Li Si’s account will become 12RMB, which is equivalent to more 10Yuanqian, isn't this bank going to lose money?

Therefore, for some database operations corresponding to state transitions in the real world, it is not only necessary to ensure that these operations are 原子性completed in a certain way, but also to ensure that other state transitions will not affect this state transition. This rule is called 隔离性. At this time, the uncles who design the database need to take some measures to make the execution order of database operations corresponding to different state transitions (T1 and T2 in the above example) accessing the same data (A account and B account in the above example) have a certain order. Regularity, this is what we will talk about in the following chapters.

1.3 Consistency

In the world we live in, there are all kinds of constraints. For example, the ID number cannot be repeated, the gender can only be male or female, the score of the college entrance examination can only be between 0 and 750, the maximum denomination of RMB can only be 100, and there are only 3 kinds of traffic lights. Color, house price cannot be negative, students should listen to the teacher, blah blah, blah, blah, blah, blah, blah, blah, blah, blah, blah. You can tell he's talking nonsense. The database world is only a mapping of the real world, and the constraints that exist in the real world must of course be reflected in the database world. If all the data in the database conform to the constraints in the real world (all defined rules), we say that the data is consistent, or consistent.

How to ensure the consistency of data in the database (that is, conform to all real-world constraints)? This actually relies on two efforts:

Aspect 1: The database itself can guarantee some consistency requirements for us (that is, the database itself can guarantee that some real-world constraints are always valid).

We know that the MySQL database can create 主键, 唯一索引,, 外键and declare a column as a table NOT NULLto reject NULLthe insertion of values. For example, when we create a unique index on a certain column, if the value of the column is repeated when inserting a certain record, MySQL will report an error and refuse to insert. In addition to these functions of ensuring consistency that we are already very familiar with, MySQL also supports the CHECK syntax to define constraints, such as this:

CREATE TABLE account (
    id INT NOT NULL AUTO_INCREMENT COMMENT '自增id',
    name VARCHAR(100) COMMENT '客户名称',
    balance INT COMMENT '余额',
    PRIMARY KEY (id),
    CHECK (balance >= 0)
);

The original intention of the statement in the above example CHECKis to stipulate that balancethe column cannot store 0a number less than, and the corresponding meaning in the real world is that the bank account balance cannot be less than 0. But unfortunately, MySQL仅仅支持 CHECK语法,但实际上并没有一点卵用that is to say, even if we use the above-mentioned CHECKtable-building statement with clauses to create accounta table, MySQL will not check whether the constraints in the CHECK clause are established when inserting or updating records.

小提示:
Some other databases, such as the CHECK syntax supported by SQL Server or Oracle, have a real effect. Before inserting or updating records, it will check whether the data meets the constraints specified in the CHECK clause. If not Otherwise, the insert or update will be rejected.

Although CHECKclauses are useless for consistency checks, we can still define some constraints by defining triggers to ensure the consistency of data in the database.

Aspect 2: More consistency requirements need to be guaranteed by programmers who write business code.

In order to establish the corresponding relationship between the real world and the database world, theoretically all the constraints in the real world should be reflected in the database world, but unfortunately, it is a performance-intensive job to perform a consistency check when changing database data, for
example We accounthave created a trigger for the table. Whenever a record is inserted or updated, it will check whether the value of the balancecolumn is greater than 0, which will affect the speed of insertion or update. It is not a big problem just to verify that a row of records does not meet the consistency requirements. Some consistency requirements are simply abnormal. For example, the bank will create a table representing the bill, which records every transaction of each account. , 每一笔交易完成后,都需要保证整个系统的余额等于所有账户的收入减去所有账户的支出. If this consistency requirement is implemented at the database level, every time a transaction occurs, it is necessary to add up all income and subtract all expenses, and then add up all account balances to see if the two values ​​are not equal. Isn’t this funny? If there are hundreds of millions of records in the bill table, the verification process alone may take several hours. That is to say, if you buy pancakes at a pancake stand, you have to wait for several hours after paying with your bank card. It takes hours to prompt that the payment is successful, such a performance cost is completely unaffordable.

Complex consistency requirements abound in real life, but due to performance problems, it is unrealistic to hand over the consistency requirements to the database, so this pot is thrown to the business-side programmers. For example, for our accounttable, we don’t need to create a trigger, as long as the programmer who writes the business judges in his own business code, when an operation will balanceupdate the value of the column to a value less than 0, it will not be executed It should work just fine!

What we have been nagging about 原子性and 隔离性will have 一致性an impact on it. For example, after the transfer operation in our real world is completed, there is a 一致性requirement that the total balance of the accounts participating in the transfer remain unchanged. If the database does not follow 原子性the requirements, that is, it will not be transferred after half of the transfer, that is to say, the money is deducted from Zhang San but not transferred to Li Si, then it does not meet the 一致性requirements in the end; similarly, if the database does not follow 隔离性the requirements, it is like As mentioned in the example we mentioned earlier 隔离性when we were nagging, the money deducted from Zhang San’s account may be different from the money increased in Li Si’s account, which means that it does not meet the 一致性needs. So say, 数据库某些操作的原子性和隔离性都是保证一致性的一种手段,在操作执行完成后保证符合所有既定的约束则是一种结果. 原子性Does the operation that satisfies the 隔离性sum must be satisfied 一致性? That's not necessarily true. For example, Zhang San wants to transfer 20 yuan to Li Si. Although he is satisfied 原子性, 隔离性the balance of Zhang San's account will become negative after the transfer is completed, which is obviously unsatisfactory 一致性. Is the operation that does not satisfy 原子性the 隔离性sum necessarily unsatisfactory 一致性? This is not necessarily the case, as long as the final result complies with all real-world constraints, then it complies 一致性.

1.4 Durability

When a state transition in the real world is completed, the result of this transition will be permanently retained. This rule is called by the uncles who design the database 持久性. For example, if Zhang San transfers money to Li Si, when the ATM prompts that the transfer is successful, it means that the account status transition is completed, and Zhang San can withdraw his card and leave. If after Zhang San leaves, the bank cancels the transfer operation and returns to the state before the transfer, then Li Si still has no money, so this 持久性is very important. When mapping the state transition of the real world to the database world, persistence means that the data modified by the database operation corresponding to the transition should be retained on the disk. No matter what happens after the accident, the impact of this transition will not be should be lost.

2. The concept of business

In order to make it easier for everyone to remember the 4 characteristics that need to be observed during the transition process of the real world state we talked about above, we extract the initials of the English words corresponding to these four words, 原子性(Atomicity), 隔离性(Isolation), 一致性(Consistency)and these four words , and change the order slightly to form a complete English word for: . Presumably everyone has learned English in junior high school and high school. ACID means acid in English. When we mention the word ACID in the future, everyone should think of the rules of atomicity, consistency, isolation, and persistence. In addition, for the sake of convenience, the uncle who designed the database called one or more database operations that need to be guaranteed , , and as one (the English name is: ).持久性(Durability)A、I、C、DACID原子性隔离性一致性持久性事务transaction

We now know that it is an abstract concept, which actually corresponds to one or more database operations. The uncle who designed the database roughly divides it into the following states 事务according to the different stages of these operations:事务


  • When the database operation corresponding to an active (active) transaction is being executed, we say that the transaction is in progress 活动的状态.

  • Partially committed (partially committed)
    When the last operation in the transaction is executed, but because the operations are executed in memory, the impact is not flushed to disk, we say that the transaction is in progress 部分提交的状态.

  • Failed (failed)
    When the transaction is in the active or partially committed state, it may encounter some errors (database error, operating system error, or direct power failure, etc.) and cannot continue to execute, or artificially stop the current transaction. The execution of the transaction, we say that the transaction is in 失败的状态.

  • Aborted (aborted)
    If the transaction is executed halfway 失败的状态, such as the transfer transaction from Zhang San to Li Si we talked about before, when the money in Zhang San's account was deducted, but the money in Li Si's account did not increase, an error occurred , so that the current transaction is in place 失败的状态, then it is necessary to adjust the modified account balance of Zhang San to the amount before the transfer. In other words, it is necessary to cancel the impact of the failed transaction on the current database. In written words, we call this process of revocation 回滚. When 回滚the operation is completed, that is, the database is restored to the state before the execution of the transaction, we say that the transaction is in progress 中止的状态.

  • Committed (committed)
    When a transaction in a partially committed state synchronizes all modified data to disk, we can say that the transaction is in place 提交的状态.

As the database operations corresponding to the transaction are executed at different stages, the state of the transaction is also changing. A basic state transition diagram is as follows:

insert image description here
It can also be seen from the figure that 只有当事务处于提交的或者中止的状态时,一个事务的生命周期才算是结束了. For a transaction that has been committed, the modifications made by the transaction to the database will take effect permanently, and for a transaction that is in an aborted state, all modifications made by the transaction to the database will be rolled back to the state before the transaction was executed.

小提示:
Everyone knows that our computer terms are basically translated from English to Chinese. The English of affairs is transaction, and the English literal translation means transaction. The meaning of buying and selling is that the buyer pays and the seller delivers the goods. No delivery, no payment after delivery, so the transaction itself is an inseparable operation. I don’t know which great god translated transaction into transaction (I think they can’t think of any better words, so they can only find one at random). The word transaction has no meaning of transaction or sale at all, so It will be more difficult for everyone to understand. Foreigners may understand transaction better~

3. The syntax of transactions in MySQL

We say that the essence of a transaction is actually just a series of database operations, but these database operations conform to ACIDthe characteristics, so how to put certain operations in a transaction to execute in MySQL? Let's focus on nagging next.

3.1 Start a transaction

We can use one of the following two statements to start a transaction:

Statement one: BEGIN [WORK];

BEGINThe statement represents opening a transaction, and the following words WORKare optional. After starting the transaction, you can continue to write several statements, all of which belong to the transaction just started.

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)
mysql> 加入事务的语句...

Statement two: START TRANSACTION;

START TRANSACTIONStatements and BEGINstatements have the same effect, and both mark the opening of a transaction, such as this:

mysql> START TRANSACTION;
Query OK, 0 rows affected (0.00 sec)
mysql> 加入事务的语句...

But what BEGINis a little more powerful than the statement is that there are START TRANSACTIONseveral modifiers that can be followed by the statement, just a few of them:

  • 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.

    小提示:
    In fact, read-only transactions are only allowed to modify the data in tables that other transactions can also access. For temporary tables (the tables we create using CREATE TMEPORARY
    TABLE), since they can only be seen in the current session, only In fact, read transactions can also add, delete, and modify temporary tables.

  • READ WRITE: Indicates that the current transaction is a read-write transaction, that is, the database operations belonging to this transaction can either read data or modify data.

  • WITH CONSISTENT SNAPSHOT: Start consistent reading (don't worry about what is a consistent reading, the following chapters will be nagging).

For example, if we want to start a read-only transaction, just add READ ONLYthis modifier directly START TRANSACTIONafter the statement, for example:

START TRANSACTION READ ONLY;

If we want to TART TRANSACTIONfollow more than one S 修饰符, we can use commas to 修饰符separate them. For example, to open a read-only transaction and consistent read, we can write like this:

START TRANSACTION READ ONLY, WITH CONSISTENT SNAPSHOT;

Or open a read-write transaction and consistent read, you can write like this:

START TRANSACTION READ WRITE, WITH CONSISTENT SNAPSHOT

However, one thing that everyone needs to pay attention to here is that READ ONLYand READ WRITEis used to set the so-called transaction access mode, that is, to access the data in the database in a read-only or read-write manner. The access mode of a transaction cannot be set to read-only at the same time. is also set to read-write, so we can't put READ ONLYand READ WRITEafter START TRANSACTIONthe statement at the same time. Also, if we don't explicitly specify a transaction's access mode, then the transaction's access mode is 读写the mode.

3.2 Submit the transaction

After starting the transaction, you can continue to write the statements that need to be placed in the transaction. After the last statement is written, we can submit the transaction. The submitted statement is also very simple:COMMIT [WORK]

COMMITThe statement represents the submission of a transaction, and the following WORKis dispensable. For example, we said above that Zhang San transferred 10 yuan to Li Si, which actually corresponds to two statements in MySQL. We can put these two statements into one transaction. The complete process is as follows:

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> UPDATE account SET balance = balance - 10 WHERE id = 1;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> UPDATE account SET balance = balance + 10 WHERE id = 2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> COMMIT;
Query OK, 0 rows affected (0.00 sec)

3.3 Manually abort the transaction

If we write a few statements and find that one of the above statements is wrong, we can manually use the following statement to restore the database to the way it was before the transaction was executed:ROLLBACK [WORK]

ROLLBACKThe statement means to suspend and roll back a transaction, and the following WORKare optional and similar. For example, when we wrote the MySQL statement corresponding to the transfer of 10 yuan from Zhang San to Li Si, we first deducted 10 yuan from Zhang San, and then only added 1 yuan to Li Si's account for a while, and then we can use the statement to roll back ROLLBACK. The complete process is like this:

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> UPDATE account SET balance = balance - 10 WHERE id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> UPDATE account SET balance = balance + 1 WHERE id = 2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> ROLLBACK;
Query OK, 0 rows affected (0.00 sec)

It needs to be emphasized here that ROLLBACKthe statement is used by our programmers to manually roll back the transaction. If the transaction encounters some errors during execution and cannot continue to execute, the transaction will be automatically rolled back.

小提示:
The syntax of opening, submitting, and aborting transactions we are talking about here is only for the syntax of controlling transactions when interacting with the server through the mysql client program when using the black box. If you use other client programs, such as JDBC , then you need to refer to the corresponding documentation to see how to control transactions.

3.4 Storage Engines Supporting Transactions

Not all storage engines in MySQL support transaction functions. Currently, only InnoDBstorage NDBengines that support transactions (if a transaction includes modifying a table that uses a storage engine that does not support transactions, then the storage engine that does not support transactions The changes made to the table will not be rolled back. For example, we have two tables, tbl1using a storage engine that supports transactions InnoDB, and tbl2a storage engine that does not support transactions MyISAM. Their table creation statements are as follows:

mysql> CREATE TABLE demo14 (
    i int
) engine=InnoDB;
Query OK, 0 rows affected (0.05 sec)

mysql> CREATE TABLE demo15 (
    i int
) ENGINE=MyISAM;
Query OK, 0 rows affected (0.01 sec)

Let's take a look at the difference between starting a transaction first, writing an insert statement and then rolling back the transaction demo14:demo15

mysql> SELECT * FROM demo14;
Empty set (0.00 sec)

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO demo14 VALUES(1);
Query OK, 1 row affected (0.00 sec)

mysql> ROLLBACK;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM demo14;
Empty set (0.00 sec)

It can be seen that for a table that uses a storage engine that supports transactions demo14, after we insert a record and roll back, demo14it returns to the state when no record was inserted. Look at the performance of the table again demo15:

mysql> SELECT * FROM demo14;
Empty set (0.01 sec)

mysql> SELECT * FROM demo15;
Empty set (0.00 sec)

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO demo15 VALUES(1);
Query OK, 1 row affected (0.00 sec)

mysql> ROLLBACK;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SELECT * FROM demo15;
+------+
| i    |
+------+
|    1 |
+------+
1 row in set (0.01 sec)

It can be seen that although we used ROLLBACKthe statement to roll back the transaction, the inserted record remained in demo15the table.

3.5 Automatic submission

There is a system variable in MySQL autocommit:

mysql> SHOW VARIABLES LIKE 'autocommit';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| autocommit    | ON    |
+---------------+-------+
1 row in set (0.00 sec)

mysql> set persist autocommit = 'ON';
Query OK, 0 rows affected (0.00 sec)

It can be seen that its default value ONis, that is to say, by default, if we do not explicitly use START TRANSACTIONor BEGINstatement to start a transaction, then each statement is regarded as an independent transaction, this feature is called the current action of the transaction submit. If we do not explicitly start a transaction with the START TRANSACTIONor statement when Zhang San transfers 10 yuan to Li Si , then the following two statements are equivalent to being executed in two independent transactions:BEGIN

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

Of course, if we want to turn off this active submission function, we can use one of the following two methods:

  • An explicit use START TRANSACTIONor BEGINstatement starts a transaction. In this way, the active commit function will be temporarily disabled before the transaction is committed or rolled back.
  • Set the value of the system variable autocommitto OFF, like this:SET autocommit = OFF;

In this case, the multiple statements we write belong to the same transaction, until we explicitly write COMMITthe statement to commit the transaction, or explicitly write ROLLBACKthe statement to roll back the transaction.

3.6 Implicit commit

When we use START TRANSACTIONthe or BEGINstatement to start a transaction, or autocommitset the value of the system variable OFFto , the transaction will not be submitted automatically, but if we enter some statements, it will be submitted quietly, just like we entered COMMITThe statement is the same, this kind of situation that causes the transaction to commit due to some special statements is called 隐式提交, these statements that will cause the transaction to commit implicitly include:

  • Define or modify the data definition language of database objects (Data definition language, abbreviated as: DDL). The so-called database objects refer to databases, tables, views, stored procedures, and so on. When we use CREATE, ALTER, DROPand other statements to modify these so-called database objects, we will implicitly commit the transaction to which the previous statement belongs, like this: #A statement
    BEGIN;
    SELECT ... in a transaction
    UPDATE ... #A statement in a transaction
    ... #Other in a transaction Statement
    CREATE TABLE ...# `This statement will implicitly commit the transaction to which the previous statement belongs

  • Implicit use or modification of mysqltables in the database
    When we use statements such as ALTER USER, CREATE USER, DROP USER, GRANT, RENAME USER, REVOKE, S, ET PASSWORDetc., the transaction to which the previous statement belongs will also be implicitly committed.

  • Transaction control or statements about locking
    When we use START TRANSACTIONor BEGINa statement to open another transaction before a transaction has been committed or rolled back, the previous transaction will be committed implicitly, such as this:
    BEGIN;
    SELECT ... #A statement in a transaction
    UPDATE ... #A statement in a transaction
    ... # Other statements in a transaction
    BEGIN;# This statement will implicitly commit the transaction to which the previous statement belongs

    Or the value of the current autocommitsystem variable OFF, ONwhen , will also implicitly commit the transaction to which the previous statement belongs.

    Or using `LOCK TABLES, UNLOCK TABLES and other statements about locking will also implicitly commit the transaction to which the previous statement belongs.

  • Statements for loading data: For example, LOAD DATAwhen we use statements to import data into the database in batches, the transactions to which the previous statements belong will also be submitted implicitly.

  • Some statements about MySQL replication will also implicitly commit the transaction to which the previous statement belongs when
    using START SLAVE, STOP SLAVE, RESET SLAVE, and other statements.CHANGE MASTER TO

  • Some other statements
    using ANALYZE TABLE, CACHE INDEX, CHECK TABLE, FLUSH, LOAD INDEX INTO CACHE, OPTIMIZE TABLE, REPAIR TABLE, RESETand other statements will also implicitly commit the transaction to which the previous statement belongs.

小提示:
Some of the statements mentioned above, if you know them all and know what they are used for, that would be great. Don’t be discouraged if you don’t know them. They are written here just for the integrity of the content. Let’s list all the situations, and what each statement is used for. Let’s talk about it when we encounter it.

3.7 Savepoints

If you have started a transaction and typed a lot of statements, and suddenly found that there is something wrong with the last statement, you have to use the statement ROLLBACKto restore the database state to the state before the transaction was executed, and then start all over again, there is always a kind of return to liberation overnight feeling before. Therefore, the database proposes a 保存点(English: savepoint) concept, which is to mark a few points in the database statement corresponding to the transaction. When we call the ROLLBACKstatement, we can specify which point it will roll to instead of returning to the original origin. The syntax for defining a savepoint is as follows:SAVEPOINT 保存点名称

When we want to roll back to a save point, we can use the following statement (the sum of the words in the following statement WORKis SAVEPOINToptional):ROLLBACK [WORK] TO [SAVEPOINT] 保存点名称

However, if ROLLBACKthe statement does not follow the name of the savepoint, it will directly roll back to the state before the transaction execution.

If we want to delete a savepoint, we can use this statement:RELEASE SAVEPOINT 保存点名称

The following is an example of Zhang San transferring 10 yuan to Li Si to show the 保存点usage. After executing the statement of deducting the money from Zhang San's account, 10元type a 保存点:

mysql> SELECT * FROM account;
+----+--------+---------+
| id | name   | balance |
+----+--------+---------+
|  1 | 张三   |      12 |
|  2 | 李四   |       2 |
+----+--------+---------+
2 rows in set (0.00 sec)

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> UPDATE account SET balance = balance - 10 WHERE id = 1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SAVEPOINT s1;    # 一个保存点
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM account;
+----+--------+---------+
| id | name   | balance |
+----+--------+---------+
|  1 | 张三   |       2 |
|  2 | 李四   |       2 |
+----+--------+---------+
2 rows in set (0.00 sec)

mysql> UPDATE account SET balance = balance + 1 WHERE id = 2; # 更新错了
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> ROLLBACK TO s1;  # 回滚到保存点s1处
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM account;
+----+--------+---------+
| id | name   | balance |
+----+--------+---------+
|  1 | 张三   |       2 |
|  2 | 李四   |       2 |
+----+--------+---------+
2 rows in set (0.01 sec)

So far, today's study is over, I hope you will become an indestructible self
~~~

You can’t connect the dots looking forward; you can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future.You have to trust in something - your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life

If my content is helpful to you, please 点赞, 评论,, 收藏creation is not easy, everyone's support is the motivation for me to persevere

insert image description here

Guess you like

Origin blog.csdn.net/liang921119/article/details/130869167
Recommended