Explain the syntax and process of MySQL transaction in detail

Hua Weiyun 2021-01-20 21:45:40
explain syntax process mysql transaction


Abstract :MySQL Provides a variety of storage engines to support transactions .

MySQL Provides a variety of storage engines to support transactions . There are storage engines that support transactions InnoDB and BDB, among ,InnoDB Storage engine transactions mainly through UNDO Journal and REDO Log implementation ,MyISAM The storage engine does not support transactions .

expand : Any kind of database , You'll have all kinds of logs , It is used to record the operation of the database 、 Daily operation 、 Error messages, etc ,MySQL No exception . for example , When the user root Log in to MySQL The server , The login time of the user will be recorded in the log file 、 Perform operations, etc .

For maintenance MySQL The server , Often needed in MySQL Log operation in the database :

  • UNDO journal : Copy pre transaction data , Used to roll back data in the event of a transaction exception .
  • REDO journal : Record in transaction execution , Every operation that updates data , When the transaction commits , The content will be refreshed to disk .

By default , Every one of them SQL Statement is a transaction , The perform SQL Automatically submit after statement . In order to achieve the purpose of taking several operations as a whole , Need to use BEGIN or START TRANSACTION Start a transaction , Or disable automatic submission of the current session .

The syntax and flow of executing transactions

SQL Use the following statement to manage transactions .

1) Start business

BEGIN;

or

START TRANSACTION;

This statement explicitly marks the starting point of a transaction .

2) Commit transaction

MySQL Use the following statement to commit the transaction :

COMMIT;

COMMIT Represents a commit transaction , That is to commit all operations of the transaction , To be specific , That is to write all the updates to the database in the transaction to the physical database on disk , The business ended normally .

Commit transaction , It means that all data executed since the beginning of the transaction is modified to be a permanent part of the database , So it also marks the end of a transaction . Once the command is executed , You will not be able to roll back the transaction . Only when all changes are ready to commit to the database , To perform this operation .

3) Roll back ( revoke ) Business

MySQL Use the following statement to roll back the transaction :

ROLLBACK;

ROLLBACK Means to undo a transaction , In other words, some kind of failure occurs in the process of transaction running , The transaction cannot continue , The system will cancel all completed operations on the database in the transaction , Roll back to the state at the beginning of the transaction . The operation here refers to the update operation of the database .

When an error is encountered during the execution of a transaction , Use ROLLBACK Statement to roll back the transaction to the starting point or the specified hold point . meanwhile , The system will clear all data changes from the beginning of the transaction or to a savepoint , And release the resources controlled by the transaction . therefore , This statement also marks the end of the transaction .

summary

BEGIN or START TRANSACTION After statement SQL Statement to update the database data will be recorded in the transaction log , Until I met ROLLBACK Sentence or COMMIT sentence . If an operation in a transaction fails and is executed ROLLBACK sentence , After the transaction statement is opened, all the updated data can be rolled back to the state before the transaction starts . If all operations in the transaction are completed correctly , And used COMMIT Statement to submit update data to the database , Then the data is in a new consistent state .

Examples demonstrate

Here are two examples to illustrate MySQL The specific usage of transaction .

example 1

The following is a simulation of the decrease of Zhang San's account 500 After the yuan , Li Si's account hasn't been increased yet 500 when , There are scenarios where other sessions access data tables . Because the code needs to be executed in two windows , For ease of reading , Here we call it A Windows and B window .

1) stay A Open a transaction in the window , And update the mybank In the database bank The data table ,SQL Statement and run results are as follows :

mysql> USE mybank;
Database changed
mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)
mysql> UPDATE bank SET currentMoney = currentMoney-500
-> WHERE customerName=' Zhang San ';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0

2) stay B Query in the window bank Data in the data table ,SQL Statement and run results are as follows :

mysql> SELECT * FROM mybank.bank;
+--------------+--------------+
| customerName | currentMoney |
+--------------+--------------+
| Zhang San | 1000.00 |
| Li Si | 1.00 |
+--------------+--------------+
2 rows in set (0.00 sec)

It can be seen from the results , although A The transaction in the window has changed bank Table data , But it didn't immediately update the data , At this time, other sessions still read the data before updating .

3) stay A Continue to execute the transaction and commit the transaction in the window ,SQL Statement and run results are as follows :

mysql> UPDATE bank SET currentMoney = currentMoney+500
-> WHERE customerName=' Li Si ';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> COMMIT;
Query OK, 0 rows affected (0.07 sec)

4) stay B Query again in the window bank Data from data sheets ,SQL Statement and run results are as follows :

mysql> SELECT * FROM mybank.bank;
+--------------+--------------+
| customerName | currentMoney |
+--------------+--------------+
| Zhang San | 500.00 |
| Li Si | 501.00 |
+--------------+--------------+
2 rows in set (0.00 sec)

stay A Execute... In the window COMMIT After committing the transaction , Updates to the data will be submitted together , Other sessions read the updated data . It can be seen from the results that the total account balance of Zhang San and Li Si is consistent with that before the transfer , So the data is updated from one consistent state to another .

Mentioned earlier , When there is a problem in the execution of a transaction , That is, when a complete transaction cannot be executed according to the normal process , have access to ROLLBACK Statement to roll back , Use data to restore to the original state .

In case 1 in , Zhang San's account balance has been reduced to 500 element , If you transfer out again 1000 element , There will be a negative balance , So you need to roll back to the original state . For example 2 Shown .

example 2

Reduce Zhang San's account balance 1000 element , And roll back the transaction ,SQL The statement and run result are as follows :

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)
mysql> UPDATE bank SET currentMoney = currentMoney-1000 WHERE customerName=' Zhang San ';
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> ROLLBACK;
Query OK, 0 rows affected (0.07 sec)
mysql> SELECT * FROM mybank.bank;
+--------------+--------------+
| customerName | currentMoney |
+--------------+--------------+
| Zhang San | 500.00 |
| Li Si | 501.00 |
+--------------+--------------+
2 rows in set (0.00 sec)

It can be seen from the results , After performing a transaction rollback , The account data is restored to its original state , The state of the transaction before execution .

expand

In database operation , In order to effectively ensure the correctness of concurrent reading data , The isolation level of transaction is proposed . In case 1 And example 2 In the demonstration of , The isolation level of the transaction is the default isolation level . stay MySQL in , The default isolation level for transactions is REPEATABLE-READ ( Can be reread ) Isolation level , That is, before the end of the transaction ( unexecuted COMMIT or ROLLBACK), Other sessions can only read uncommitted data .

matters needing attention

MySQL Transaction is a very resource consuming function , We should pay attention to the following points in the use process .

1) Keep things as short as possible

A large number of resources will be reserved in the database management system from the beginning to the end of a transaction , To ensure the atomicity of the transaction 、 Uniformity 、 Isolation and persistence . If in a multiuser system , Larger transactions will take up a lot of resources of the system , Make the system overburdened , Will affect the performance of the software , It even causes the system to crash .

2) Try to minimize the amount of data accessed in a transaction

When transactions are executed concurrently , The less data the transaction operation has , The less transactions operate on the same data .

3) Try not to use transactions when querying data

Browsing and querying data does not update the data in the database , Therefore, we should try not to use transaction to query data , Avoid taking up excessive system resources .

4) In the process of transaction processing, try not to appear the operation waiting for user input

In the course of dealing with a transaction , If you need to wait for the user to input data , So the business takes up resources for a long time , It may cause system blockage .

This article is shared from Huawei cloud community 《MySQL The syntax and flow of executing transactions 》, Original author : Lucky boy .

 

Click to follow , The first time to learn about Huawei's new cloud technology ~

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210120214451149G.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云