当前位置:网站首页>MySQL transactions and foreign keys
MySQL transactions and foreign keys
2022-06-13 05:15:00 【strive_ one】
Business
Why there's business
- Transaction is widely used in order system 、 Banking system and other scenarios
- for example :A Users and B The user is the depositor of the bank , Now? A To give B Transfer accounts 500 element , Then you need to do the following things :
- Check A The account balance of >500 element
- A Deduct... From the account 500 element
- B Add... To the account 500 element
- The normal process goes down ,A The account has been deducted 500,B Add... To the account 500, All's well that ends well . Then if A After deducting money from the account , There's something wrong with the system ,A Lost... In vain 500, and B Nor did he receive what should have belonged to him 500. In the above cases , There is a precondition hidden :A Deduction and B Add money , Or at the same time , Or fail at the same time . This is where the transaction needs to be .
- Check A The account balance of >500 element
- Business (Transaction) Is the basic unit of concurrency control . Transaction , It's a sequence of operations , These operations must be synchronized , If it is implemented, it will be implemented , If it is not implemented, it will not be implemented , It is an indivisible unit of work . for example , Bank transfer : Deduct money from one account and add money to another account , These two operations must be synchronized . therefore , They should be regarded as a business . A transaction is a unit in which a database maintains data consistency , At the end of each transaction , Can keep data consistent .
- Once the transaction is started , Then updating the database will not immediately affect the source database , Only after the success, the submitted operation will be executed , Changes will be submitted to the source database
Four characteristics of transactions ( abbreviation ACID)
- 1、 Atomicity (Atomicity): All operations in a transaction are indivisible in the database , It's synchronous , If you do, do it all , If not implemented , Just don't do it all .
- 2、 Uniformity (Consistency): Several transactions executed in parallel , The execution result must be consistent with the result of serial execution in a certain order .
- 3、 Isolation, (lsolation): The execution of the transaction is not interfered by other transactions , The intermediate result of transaction execution must be transparent to other transactions .
- 4、 persistence (Durability): For any committed transaction , The system must ensure that the changes of the transaction to the database are not lost , Even if the database fails .
Transaction usage considerations
- requirement : The engine type of the table must be innodb Type can only be used for transaction .
- View the creation statement of the table , You can see engine=innodb:

- A command to modify data triggers a transaction , Include insert、update、delete
By default, a terminal is opened to start transactions , This transaction will be submitted automatically . - Be careful : When a transaction is started manually , Must be submitted manually , Otherwise, the operation will not be reflected in the database .
Open transaction begin:
- Execute the modify command after starting the transaction , Changes are maintained in the local cache , Instead of maintaining it in the physical table , After the transaction is started, all operations should not be immediately reflected on the data table .


- Next, modify the data


- Reopen a terminal , Check the contents of the table

Commit transaction commit
- Maintain the data changes in the cache into the physical table , Now we are opening the terminal window of the transaction , Conduct commit;
- So in the connection that does not have a transaction open , Then you can see the data information .

Roll back the transaction rollback: Discard changed data in cache


- We find that the data message is gone . however , When we insert data information again , Data table id Information , No, it's not 20 了 , because 20 It has been used .

- The actual code is written as follows :

Business
- Can pass begin Manually open transaction
- Once the transaction is started , Update the current situation , Will not immediately affect the original database , Wait until all sql After successful execution , Manual commit( Submit ) Will affect the original database , When the transaction is not started manually , Transactions are also open , However, the commit operation is performed automatically
- If a large number of data are updated , How efficient is it to start a transaction manually ?
- When updating data in large quantities, you need to manually start the transaction .
- Improve the efficiency of updates , More secure
Business management :
- Transaction processing mechanism plays a very important role in the process of program development , It can make the whole system more secure , Ensure the synchronization of operations in the same transaction .
Concept of transactions
- in real life , People often transfer money , The transfer can be done in two parts , Transfer in and transfer out , Only when these two parts are completed can the transfer be considered successful . In the database , This process is done with two statements , If any one of the statements has an exception and is not executed , The amounts of the two accounts will not be synchronized , Cause mistakes .
- In order to prevent the above situation ,mysql Transaction is introduced in , A transaction is a set of operations on a database , It can be made up of one or more mysql Sentence composition , The operation of the same transaction has the characteristics of synchronization , If one of the statements cannot be executed , Then all statements will not be executed , in other words , All statements in a transaction are either executed , Either not .
- When using transactions in a database , The transaction must be started first , The statement to start a transaction is as follows :
- start transaction;
- After the transaction is started, you can execute SQL sentence ,SQL After the statement is executed successfully , You need to commit the transaction with the appropriate statement . The statement to commit a transaction is as follows :
- commit;
- It should be noted that : stay mysql Written directly in sql Statements are submitted automatically , The operation statements in the transaction need to use commit Statement manual commit , Only after the transaction is committed will the operations take effect .
- If you do not want to commit the current transaction, you can also cancel the transaction with related statements ( Also known as rollback ), The rollback statement is as follows :
- rollback;
- It should be noted that :rollback Statement can only rollback uncommitted transactions , Committed transactions cannot be rolled back .
Use the case of transfer to demonstrate how to use transactions :
preparation :






Open transaction , And then through update Statement will a account 100 Yuan to b Account , Last commit transaction :



Commit transaction

The transfer function has been successfully completed through transactions .
It should be noted that : Two of the above update If an error occurs in any statement in the statement, the transaction will not be committed , thus , If an exception occurs before the transaction is committed , The uncommitted operations in the transaction will be cancelled , Therefore, transaction synchronization can be guaranteed .
Transactions are strictly defined , It must satisfy at the same time 4 A feature :
- Atomicity (Atomicity)
- Uniformity (Consistency)
- Isolation, (Isolation)
- persistence (Durability)
It is also known as ACID standard .
- Atomicity :
- Atomicity means that a transaction must be regarded as an indivisible minimum unit of work , Only all database operations in the transaction are successful , The whole transaction is successful , If there is any one in the transaction SQL Statement execution failed , Has been implemented successfully SQL The statement must also undo , The state of the database returns to the state before the transaction is executed .
- Uniformity :
- Consistency refers to a transaction that changes a database from one state to the next consistent state . for example : One field in the table is name , Have unique constraints , That is, the name cannot be repeated , If a transaction changes the name , Make the name not unique , This breaks the consistency requirement of the transaction , If an action in a transaction fails , The system can automatically amortize transactions , Returns the status of initialization .
- Isolation, :
- Isolation can also be called concurrency control 、 Serializable , Locks, etc. , When multiple users access the database concurrently , A transaction opened by a database for each user , Can't be disturbed by the operation data of other transactions , Multiple concurrent transactions should be isolated from each other .
- persistence :
- Once the transaction is committed , The changes will be permanently saved to the database , Even if the database fails, it should not be affected . It should be noted that , Transaction persistence cannot be achieved 100% 's persistence , Permanence can only be guaranteed from the perspective of the transaction itself , And some external reasons lead to database failure , If the hard disk is damaged , Then all submitted data may be lost .
边栏推荐
- C language learning log 1.22
- Small project - household income and expenditure software (1)
- MySQL log management and master-slave replication
- Dynamic programming - longest common substring
- C language learning log 10.10
- lookup
- [thread / multithread] execution sequence of threads
- Chapter 17 free space management
- Pyqt5 controls qpixmap, qlineedit qsplitter, qcombobox
- Qmessagebox in pyqt5
猜你喜欢

Chapter 18 pagination: Introduction

ZABBIX proxy, sender (without agent monitoring), performance optimization

C language learning log 1.22

Spread your wings and soar

Metartc4.0 integrated ffmpeg compilation

Use of natural sorting comparable

QT direction key to move focus

Bomb disposal cat

Simple sr: Best Buddy Gans for highly detailed image super resolution Paper Analysis

Pycharm错误解决:Process finished with exit code -1073741819 (0xC0000005)
随机推荐
List collection concurrent modification exception
Simple SR: best buddy Gans for highly detailed image super resolution
Regular expressions in QT
详解OpenCV的函数cv::add(),并附各种情况的示例代码和运行结果
Chapter 2 process management
Install harbor (online offline)
COAP protocol libcoap API
基于 Docker Compose 搭建 Nacos 2(使用 MySQL 进行持久化)
Advanced C - Section 2 - pointers
Case - the ArrayList collection stores student objects and traverses them in three ways
Dynamic and static libraries
Modification and analysis of libcoap source code by Hongmeng device discovery module
SQL table columns and statements of database
KVM hot migration for KVM virtual management
Standard input dialog for pyqt5 qinputdialog
Violence enumeration~
Spread your wings and soar
C language learning log 10.19
Explain the opencv function cv:: add() in detail, and attach sample code and running results of various cases
Brick story