[MySQL] Talking about business

Hello, everyone~ I am your old friend: Protect Xiao Zhou ღ  


When it comes to "business", maybe everyone will have a big question in their minds? , the blogger’s understanding-transaction is a mechanism to solve the data security problem caused by the data modification of the same storage space in the MySql database in a multi-threaded environment. The essence is to package multiple SQL statements into a whole, or all of them are executed successfully. , or do not execute, when the sql statement is executed in the middle, it will be "serviced", which will cause data security problems.


This issue is included in the blogger's column : JavaEE_Protect Xiao Zhouღ's Blog-CSDN Blog

Suitable for programming beginners, interested friends can subscribe to view other "JavaEE Basics".
Stay tuned for more highlights: Protect Xiaozhou ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★*'


1. Affairs

The essence of MySql is a mechanism of interaction between the client and the server. After the two parties establish a connection, the client sends a request to the MySql server by using sql statements. The server receives and parses the request, and then "takes out" relevant data on the hard disk. As a response back to the client, the client presents the data to the user in the form of a temporary table. MySql uses hard disk as storage medium.

With the above mechanism, if multiple clients add, delete, check and modify data stored on the server at the same time, it may cause data security problems

For example 1: 

​For example 2:

MySql's transaction is to solve the above problems. 

The essence of a transaction is to package multiple sql statements into a whole. Either all of them are executed successfully, or they are not executed. When the sql statement is executed in the middle, it will "downtime", causing data security problems, and the transaction will execute the modified data. "Rollback" (rollback), restore the data to the state before it was executed, subjectively it looks like it has not been executed.

And solve the data security problem caused by multi-thread (multiple execution streams) modifying data in the same storage space.

1.1 Use of transactions

1. Start the transaction: start transaction

2. Execute multiple SQL statements

3. Rollback transaction: rollback / Commit transaction: commit

rollback means that all executions failed, and commit means that all executions were successful

start transaction; // 开启事务

update balance set balance = balance - 100 where name = "张三";
update balance set balance = balance + 100 where name = "李四";

commit; //提交事务

 In this way, multiple sql statements are packaged into a whole, which can be understood as: a relatively "thick" instruction.


1.2 Characteristics of transactions

Regarding database transactions, there are four key features: Knock on the blackboard, classic interview questions~

  1. Atomicity: Atom, the first time we heard this term should be learned from junior high school chemistry class, refers to the basic particles that cannot be divided into chemical reactions. Therefore, the atomicity of the transaction, the sql statements contained in the transaction are a whole, either all of them are executed , or none of them are executed. Roll to restore the data to the state before it was modified.
  2. Consistency : Before and after transaction execution, the data is reliable (same as the expected result). (mainly related to the atomicity of transactions)
  • Inconsistent example :
  • Pay multiple times and only deduct once (or pay once and deduct multiple times).
  • The transfer is successful, but the balance of the payer has not been deducted, or the balance of the recipient has not increased.
  • The transfer was successful, I only transferred 500 to you, but your account was 5000 more

    3. Persistence: The content modified by the transaction is written to the hard disk ( mysql uses the hard disk as the storage medium ), and the data is persistent and will not be lost due to restart.

    4. Isolation: The so-called isolation is to solve the problems caused by multiple execution streams and "concurrent" execution transactions . This is related to multi-thread security issues. Call handles this case - transfer.

For example: a restaurant has only one window, but it needs to provide dining services to multiple customers at this time. From the perspective of the waiter, if customers rush to send requests, and the waiter is in a hurry, the customer's dining information may be lost. Wrong writing (less writing, missing writing, wrong writing, etc.). If customers line up and come one by one, the quality of the waiter's work will be greatly improved. In the case of multi-threading (execution flow), the server processes the requests of reading a client at the same time, and this operation is called "concurrency".

The isolation of transactions means that there will be no problems when the database processes transactions concurrently .


1.3 Problems that may arise from concurrent execution of transactions

1.3.1 Dirty read problem

The problem of dirty reading, the meaning of "invalid" in the meaning of dirty , is not a derogatory term.

An execution flow A is modifying the data corresponding to the sql modified by the transaction S (reading to the memory), and before writing the data back to the hard disk, the execution flow B also reads the data corresponding to the sql modified by the transaction S. The operation of executing stream B to read is called "dirty read", and the read data is also called "dirty data"—invalid data, because, after executing stream A to write data back to the hard disk, the execution stream The data read by B before this is meaningless. Take the transfer scenario 2 above as an example.

In order to solve the problem of dirty reading, mysql introduces a mechanism such as "write lock".

When I am writing (modifying the data), other people cannot read the data (to avoid the invalidation of the read data), and the "write operation" and "read operation" cannot be performed at the same time (concurrent).

Of course, locking has both advantages and disadvantages. Adding locks to "write operations" reduces the degree of concurrency (efficiency of execution). When I write, other people need to wait for me to finish writing, which improves isolation—multiple execution streams The impact of data accuracy is getting smaller and smaller.


1.3.2 Non-repeatable read

For write operations, it is agreed that when I write, you are not allowed to read it, and you can only read it after I submit it (this is the agreed write lock)

When I wrote it, you were waiting, and then I submitted the data of version 1, and then you can read the data. At this time, I modified the data and submitted the data of version 2. You refresh it and read it again After a while, I found that the content read for the first time is different from the content read for the second time. This problem is called "non-repeatable read".

In the case of data in the same storage space, execution flow A submits the data, and at this time execution flow B starts to read the data, and after reading the data, execution flow C also submits the data, which means that if the execution flow B Read data multiple times, and the read results are different. It is expected that within a read cycle (transaction-modified read operation), the results of multiple reads are the same. This situation is called "non-repeatable read" ".

In order to solve the problem of "non-repeatable read", mysql introduced a mechanism such as "read lock".

Convention: When an execution stream reads data, other execution streams cannot modify it before submitting it.

Through "read lock", the ability of concurrent processing of transactions is further reduced, and the isolation level of transactions is also improved.


1.3.3 Phantom read

According to the above description, in order to ensure the accuracy of data during concurrent transaction processing, mysql has agreed on "read lock" and "write lock" , which solves the problems of non-repeatable read and dirty read.

Non-repeatable read , for the same data, within a read cycle (uncommitted), the data read multiple times is the same.

The phantom reading problem is aimed at the result set of data. In a read cycle (before submission), one piece of data is read for the first time, and two pieces of data are read for the second time. The data read for the first time is also The second result set exists and has not changed. The difference is that the number of result sets has changed.

Under the premise of read lock and write lock, a transaction reads the same data twice and finds that the read data values ​​are the same, but the result sets are different. This situation is called the "phantom read" problem.

For the problem of phantom reading, the solution provided by the database is to use "serialization", abandoning multiple execution streams to process transactions concurrently, but to process transactions one by one serially - those who want to process transactions are queued up one by one.


1.4 Transaction isolation level

For the above three problems, mysql database provides different solutions, and also brings a concept, isolation level, isolation can be regarded as, the operation and data used within a transaction are isolated from other concurrent execution flows Yes, some operations need to be queued for execution.

1. There is no lock limit for read uncommitted, and the execution flow is fully concurrency, but it also means that the isolation is very low, and the accuracy of the data is difficult to guarantee.

2. For the dirty read problem, "write lock" is adopted, and when data is written, other execution streams cannot read data. read committed locks the write, which reduces the degree of concurrency of multiple execution flows and improves the isolation of multiple execution flows.

3. Repeatable read locks both writing and reading, further reducing concurrency, improving isolation, and high data accuracy.

4. serializable Serialization completely abandons parallel processing, the execution flow processes transactions one by one, and the isolation level is the highest.

The above operation is the internal mechanism of mysql.


Well, here, the bloggers in network programming have finished sharing, I hope it will be helpful to everyone, if there is anything wrong, welcome to criticize and correct. 

Thank you to everyone who read this article, and more exciting events are coming: Protect Xiaozhou ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★* 

When I met you, all the stars fell on my head ...

Guess you like

Origin blog.csdn.net/weixin_67603503/article/details/130579695