当前位置:网站首页>100 important knowledge points that SQL must master: management transaction processing
100 important knowledge points that SQL must master: management transaction processing
2022-07-02 21:49:00 【Gu Ge academic】
This chapter introduces what transaction processing is , How to use it COMMIT and ROLLBACK Statement management
Deal with .
20.1 Transaction processing
Use transactions (transaction processing), By ensuring that batches of SQL Operation either
Fully implement , Or not at all , To maintain the integrity of the database .
Just like No 12 Lesson description , Relational databases store data in multiple tables , Make data easier to manipulate
longitudinal 、 Maintenance and reuse . Don't delve into how and why to design relational databases , In a certain
To a certain extent , Well designed database schemas are associative .
Used in front of Orders Table is a good example . Order stored in Orders and
OrderItems In two tables : Orders Store actual orders , OrderItems Storage subscription
Items purchased . These two tables use what is called a primary key ( See page 1 course ) The only ID Cross correlation
United , It is also associated with other tables containing customer and product information .
The process of adding an order to the system is as follows :
(1) Check whether there are corresponding customers in the database , If it doesn't exist , Add him ;
(2) Retrieve customer information ID;
(3) stay Orders Add a row to the table , It works with customers ID Related to ;
(4) retrieval Orders New orders given in table ID;
(5) For each item ordered on OrderItems Add a row to the table , Retrieved by ID
Put it with Orders Table correlation ( And through products ID And Products Table correlation ).
Now suppose that due to some kind of database failure ( If disk space is exceeded 、 Security restrictions 、 Table lock, etc. ),
This process cannot be completed . What happens to the data in the database ?
If the fault occurs after adding customers , add to Orders Before the table , There will be no question
topic . It is perfectly legal for some customers not to have orders . When performing this procedure again , Inserted Gu
Customer records will be retrieved and used . This process can be effectively performed from the place of failure .
however , If the fault occurs during insertion Orders After line , add to OrderItems Before line ,
What do I do ? Now? , There is an empty order in the database .
To make matters worse , If the system is adding OrderItems There is a fault when I go , What do I do ? junction
As a result, there are incomplete orders in the database , And you don't know yet .
How to solve this problem ? This requires the use of transaction processing . Transaction processing is a mechanism ,
Used to manage what must be executed in batches SQL operation , Ensure that the database does not contain incomplete operation results
fruit . Using transaction processing , It can ensure that a group of operations will not stop halfway , They either completely cling
That's ok , Or not at all ( Unless specifically directed ). If no error occurs , The whole group of statements mentions
hand ( writes ) Database table ; If an error occurs , Then back off ( revoke ), Will database
Restore to a known and safe state .
Let's take another look at this example , This time we show how this process works :
(1) Check whether there are corresponding customers in the database , If it doesn't exist , Add him ;
(2) Submit customer information ;
(3) Retrieve customer information ID;(4) stay Orders Add a row to the table ;
(5) If to Orders There was a failure adding rows to the table , Back off ;
(6) retrieval Orders New orders given in table ID;
(7) For each item ordered , Add new row to OrderItems surface ;
(8) If to OrderItems There was a failure adding rows , Fallback all added OrderItems
Row sum Orders That's ok .
When using transactions , There are several recurring keywords . The following is about the transaction processing needs
A few terms to know :
Business (transaction) Refer to a group SQL sentence ;
Back off (rollback) Revocation of appointment SQL Statement procedure ;
Submit (commit) Refers to the storage of... That will not be stored SQL Statement result written to database table ;
Reservation point (savepoint) Temporary placeholder set in transaction (placeholder),
It can be posted back ( Unlike backing back the entire transaction ).
Tips : Which statements can be fallback ?
Transactions are used to manage INSERT 、 UPDATE and DELETE sentence . Can't back SELECT
sentence ( Back off SELECT Statements are not necessary ), You can't go back CREATE or DROP fuck
do . These statements can be used in transactions , But when you go back , These operations are not undone .
20.2 Control transactions
We already know what transaction processing is , Next, we will discuss the issues involved in management affairs .
Be careful : Differences in transaction implementation
Different DBMS The syntax used to implement transaction processing is different . Please
Refer to the corresponding DBMS file .
The key to managing affairs is to SQL Statement groups are broken down into logical blocks , And specify when the data
Should go back , When not to go back .
yes , we have DBMS It is required to clearly identify the start and end of the transaction block . If in SQL Server
in , The identification is as follows ( The ellipsis indicates the actual code ):
Input ▼
BEGIN TRANSACTION
...
COMMIT TRANSACTION
analysis ▼
In this case , BEGIN TRANSACTION and COMMIT TRANSACTION Sentence of
Between the SQL Must be fully implemented or not implemented .
MariaDB and MySQL The equivalent code in is :
Input ▼
START TRANSACTION
...
Oracle The grammar used :
Input ▼
SET TRANSACTION
...
PostgreSQL Use ANSI SQL grammar :
Input ▼
BEGIN
...
other DBMS Adopt variants of the above grammar . You'll find that , Most implementations do not clearly identify things
Where does the transaction end . The business is always there , Until it's interrupted . Usually , COMMIT For insurance
Save changes , ROLLBACK Used to revoke , Details are as follows .
20.2.1 Use ROLLBACK
SQL Of ROLLBACK The command is used to go back ( revoke )SQL sentence , Please look at the following sentence :
Input ▼
DELETE FROM Orders;
ROLLBACK;
analysis ▼
In this example , perform DELETE operation , And then use ROLLBACK Statement undo . Although this is not
Is the most useful example , But it does show , In the transaction block , DELETE operation ( And
INSERT and UPDATE Same operation ) It's not the end result .
20.2.2 Use COMMIT
General SQL Statements are directly executed and written for database tables . This is the so-called hidden
Submit in style (implicit commit), That is to submit ( Write or save ) The operation is automatic .
In the transaction block , Submission does not happen implicitly . however , Different DBMS There are some differences in our practice
Same as . yes , we have DBMS Deal with the transaction side by implicit commit , Others do not .
Make a clear submission , Use COMMIT sentence . Here's a SQL Server Example :
Input ▼
BEGIN TRANSACTION
DELETE OrderItems WHERE order_num = 12345
DELETE Orders WHERE order_num = 12345
COMMIT TRANSACTION
analysis ▼
In this SQL Server In the example , Delete the order completely from the system 12345 . Because it involves more
Two new database tables Orders and OrderItems , So transaction processing block is used to guarantee the order
The list is not partially deleted . final COMMIT Statement only writes changes when there are no errors . If the first
One DELETE Work , But the second failed , be DELETE Will not submit .
For in Oracle Complete the same work , It can be done as follows :
Input ▼
SET TRANSACTION
DELETE OrderItems WHERE order_num = 12345;
DELETE Orders WHERE order_num = 12345;
COMMIT;
20.2.3 Use hold points
Easy to use ROLLBACK and COMMIT sentence , You can write or undo the entire transaction . but
yes , This can only be done for simple transactions , Complex transactions may require partial commit or fallback .
For example, the process of adding an order described above is a transaction . If an error occurs , It only needs
Return to add Orders Just before you go . There is no need to go back to Customers surface ( If saved
If you are ).
To support fallback of some transactions , Placeholders must be placed in place in the transaction block . this
sample , If you need to go back , You can go back to a placeholder .
stay SQL in , These placeholders are called hold points . stay MariaDB、MySQL and Oracle in
Create placeholders , You can use SAVEPOINT sentence .
Input ▼
SAVEPOINT delete1;
stay SQL Server in , It's as follows :
Input ▼
SAVE TRANSACTION delete1;
Each reservation point should have a unique name that can identify it , So that when you go back ,DBMS know
Back to where . To go back to the reservation point given in this example , stay SQL Server It can be carried out as follows .
Input ▼
ROLLBACK TRANSACTION delete1;
stay MariaDB、MySQL and Oracle in , It's as follows :
Input ▼
ROLLBACK TO delete1;
Here is a complete SQL Server Example :
Input ▼
BEGIN TRANSACTION
INSERT INTO Customers(cust_id, cust_name)
VALUES(1000000010, 'Toys Emporium');
SAVE TRANSACTION StartOrder;
INSERT INTO Orders(order_num, order_date, cust_id)
VALUES(20100,'2001/12/1',1000000010);
IF @@ERROR <> 0 ROLLBACK TRANSACTION StartOrder;
INSERT INTO OrderItems(order_num, order_item,
*prod_id, quantity, item_price)
VALUES(20100, 1, 'BR01', 100, 5.49);
IF @@ERROR <> 0 ROLLBACK TRANSACTION StartOrder;
INSERT INTO OrderItems(order_num, order_item,
*prod_id, quantity, item_price)
VALUES(20100, 2, 'BR03', 100, 10.99);
IF @@ERROR <> 0 ROLLBACK TRANSACTION StartOrder;
COMMIT TRANSACTION
analysis ▼
The transaction block here contains 4 strip INSERT sentence . In the first one INSERT Sentence of
Then a reservation point is defined , therefore , If any of the following INSERT operation failed ,
Transaction processing can fall back here . stay SQL Server in , You can check one named @@ERROR
The variable of , See whether the operation is successful .( other DBMS Use different functions or variables to return this
Information .) If @@ERROR Return to a non 0 Value , Something wrong has happened , Transaction processing back
Back to the reservation point . If the whole transaction is successful , Release COMMIT To retain data .
Tips : The more reserves, the better
Can be in SQL Set any number of retention points in the code , The more the better . Why? ? because
The more points to keep , The more flexible you are to fallback .
边栏推荐
- Basic knowledge of tree and binary tree (detailed illustration)
- Destroy in beforedestroy invalid value in localstorage
- The web version of xshell supports FTP connection and SFTP connection
- [shutter] shutter layout component (Introduction to layout component | row component | column component | sizedbox component | clipoval component)
- Structure array, pointer and function and application cases
- MySQL learning record (2)
- Market trend report, technical dynamic innovation and market forecast of China's low gloss instrument
- 【剑指 Offer】57. 和为s的两个数字
- Daily book CSO advanced road first exposed
- Construction and maintenance of business websites [6]
猜你喜欢
Etcd raft protocol
[shutter] shutter page Jump (route | navigator | page close)
MySQL learning record (8)
[zero foundation I] Navicat download link
TinyMCE visual editor adds Baidu map plug-in
Browser - clean up the cache of JS in the page
图像基础概念与YUV/RGB深入理解
Structure array, pointer and function and application cases
#include<>和#include“”的区别
How to write a good program when a big book speaks every day?
随机推荐
Research Report on market supply and demand and strategy of microplate instrument industry in China
[shutter] shutter layout component (Introduction to layout component | row component | column component | sizedbox component | clipoval component)
Accounting regulations and professional ethics [16]
Free open source web version of xshell [congratulations on a happy new year]
MySQL inserts Chinese data and reports an error. Set the default collation
China plastic bottle market trend report, technological innovation and market forecast
如何防止你的 jar 被反编译?
【零基础一】Navicat下载链接
treevalue——Master Nested Data Like Tensor
Micro SD Card Industry Research Report - market status analysis and development prospect forecast
Golang embeds variables in strings
China plastic box market trend report, technological innovation and market forecast
China's log saw blade market trend report, technological innovation and market forecast
VIM command-t plugin error: unable to load the C extension - VIM command-t plugin error: could not load the C extension
GEE:(二)对影像进行重采样
Construction and maintenance of business website [3]
Analysis of neural network
MySQL learning record (9)
Research Report on market supply and demand and strategy of China's plastic pump industry
The neo4j skill tree was officially released to help you easily master the neo4j map database