当前位置:网站首页>MySQL transaction
MySQL transaction
2022-07-02 09:44:00 【niceyz】
Contents of this article :
1. Transaction introduction
2. Introduction to business
1. Command line Demo
2. Code demonstration
3. Transaction features
4. Transaction isolation level
1. Safe hidden trouble
a. The question of reading
b. Writing questions
2. Isolation level
a. Read uncommitted
b. Read submitted
c. Repeatable
d. serialize | Serialization
5. Business management
1. Three layer structure introduction
2. Transaction management in the three-tier structure
a. Pass on Connection
b. Use ThreadLocal
1. Transaction introduction
A transaction is a set of operations consisting of multiple micro logical units , Only one of the logics failed , Then this set of operations will all end in failure , There is no half success , Half the unsuccessful situation .
Examples of bank transfers , Add records to two tables at one time ( One deduction , One plus ), You need to ensure that these two tables can be added successfully , A table is not allowed to succeed , A table fails .
2. Introduction to business
1. Command line Demo
Open transaction :
start transaction;
Commit transaction Make the operation effective :
commit;
Roll back the transaction Go back to the old days :
rollback;
By default ,mysql After executing each line of command , It will take effect immediately ,
Because there is a switch inside commit = on | 1 By default, submit immediately after executing a line of commands , Immediate effect
Query the submitted switch :
show variables like '%commit%';
Turn off the default submit switch :
set autocommit = off;
# Create database
DROP DATABASE yz_tran;
CREATE DATABASE yz_tran;
# Create table
CREATE TABLE `account` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) DEFAULT NULL,
`money` DECIMAL(14,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
# Add data
INSERT INTO account(NAME,money)VALUES
(" Zhang San ",1000),
(" Li Si ",1000);
SELECT * FROM `account`;
cmd Connect MySQL:
mysql –u root –p Enter password to connect mysql
Add money 、 Deduction operation :
mysql> use yz_tran;
Database changed
mysql> update account set money= money-100 where id = 1;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 900.00 |
| 2 | Li Si | 1000.00 |
+----+------+---------+
2 rows in set (0.00 sec)
mysql> update account set money= money+100 where id = 1;
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1000.00 |
| 2 | Li Si | 1000.00 |
+----+------+---------+
2 rows in set (0.00 sec)
Open transaction :
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)
mysql> update account set money= money-100 where id = 2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Inquire about , The amount here decreases , Note that this is data in memory
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1000.00 |
| 2 | Li Si | 900.00 |
+----+------+---------+
2 rows in set (0.00 sec)
Refresh on another client , The amount has not changed :
mysql> update account set money= money+100 where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Inquire about , Here the amount increases , Note that this is data in memory
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1100.00 |
| 2 | Li Si | 900.00 |
+----+------+---------+
2 rows in set (0.00 sec)
Refresh on another client , The amount remains unchanged :
Commit transaction , The operation just now confirmed that there is no problem , Make the transaction effective :commit;
mysql> commit;
Query OK, 0 rows affected (0.03 sec)
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1100.00 |
| 2 | Li Si | 900.00 |
+----+------+---------+
2 rows in set (0.00 sec)
Refresh on another client , The amount has changed :
Operation repudiation , Wrong person , Don't want to transfer ( Or the code is abnormal ) Before returning :
Open transaction :
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)
Wrong turn :
mysql> update account set money= money-100 where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1000.00 |
| 2 | Li Si | 900.00 |
+----+------+---------+
2 rows in set (0.00 sec)
Roll back :
mysql> rollback;
Query OK, 0 rows affected (0.03 sec)
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1100.00 |
| 2 | Li Si | 900.00 |
+----+------+---------+
2 rows in set (0.00 sec)
Other client queries , Or the original amount :
By default ,mysql After executing each line of command , It will take effect immediately , Because there is a switch inside commit = on | 1 By default, submit immediately after executing a line of commands , Immediate effect
Query the submitted switch :
mysql> show variables like '%commit%';
Turn off the default submit switch :
mysql> set autocommit = off;
Query OK, 0 rows affected (0.00 sec)
Turn off auto submit , Manual submission is required :
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1100.00 |
| 2 | Li Si | 900.00 |
+----+------+---------+
2 rows in set (0.00 sec)
mysql> update account set money= money-100 where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1100.00 |
| 2 | Li Si | 900.00 |
+----+------+---------+
2 rows in set (0.00 sec)
mysql> update account set money= money-100 where id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from account;
+----+------+---------+
| id | name | money |
+----+------+---------+
| 1 | Zhang San | 1000.00 |
| 2 | Li Si | 900.00 |
+----+------+---------+
2 rows in set (0.00 sec)
Other client queries , The amount has not really changed :
mysql> commit;
Query OK, 0 rows affected (0.10 sec)
commit After submission , The amount is reduced :
2-2. Code demonstration
Tool class :
public class JdbcUtil {
static ComboPooledDataSource dataSource = null;
static {
dataSource = new ComboPooledDataSource();
}
/**
* Get the connection object
* @return
*/
public static Connection getConn(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void close(Connection conn , Statement statement){
close(conn , statement , null);
}
/**
* Close the connection , Release resources
*/
public static void close(Connection conn , Statement statement , ResultSet rs){
try {
if(rs != null){
rs .close();
}
if(statement != null){
statement .close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
c3p0-config.xml
<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
<default-config>
<!-- Configure database connection information -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///yz_tran</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- Initialize the number of connections -->
<property name="initialPoolSize">10</property>
<!-- Maximum free time , If you exceed this free time , Just reset the connection object -->
<property name="maxIdleTime">30</property>
<!-- maximum connection -->
<property name="maxPoolSize">100</property>
<!-- Minimum connections -->
<property name="minPoolSize">10</property>
<!-- Maximum execution statement sentence -->
<property name="maxStatements">200</property>
</default-config>
</c3p0-config>
Test class :
public class TestTransaction {
private static final String TAG = "TestTransaction";
@Test
public void testDemo(){
Connection conn = null;
PreparedStatement ps = null;
try {
//1. Get the connection
conn = JdbcUtil02.getConn();
// Open transaction set autocommit = off;
conn.setAutoCommit(false);
//2. Transfer accounts
String sql = "update account set money = money - ? where id = ?";
// Three bucks per piece
ps= conn.prepareStatement(sql);
ps.setInt(1,100);
ps.setInt(2,1);
ps.executeUpdate();
int a = 1 /0 ;
// Li Si adds money
ps.setInt(1,-100);
ps.setInt(2,2);
ps.executeUpdate();
System.out.println(" Transfer completed ");
// Commit transaction
conn.commit();
} catch (Exception e) {
e.printStackTrace();
System.out.println(" Transfer failure ");
try {
// Transfer exception rollback transaction occurs
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
JdbcUtil02.close(conn , ps);
}
}
}
see MySQL Isolation level :
The old version mysql It's using tx_isolation
The new version mysql It's using transaction_isolation
mysql> select @@transaction_isolation;
+-------------------------+
| @@transaction_isolation |
+-------------------------+
| REPEATABLE-READ |
+-------------------------+
1 row in set (0.00 sec)
3. Transaction features ACID
Atomicity (Atomicity): All the logic in the transaction should be executed , An integral .( Atom is the smallest unit in Physics )
Uniformity (Consistency): The result of transaction execution must be to change the database from one consistency state to another
Isolation, (Isolation): The execution of one transaction cannot affect the execution of other transactions , In other words, the operation and data used in one transaction are isolated from other transactions , During concurrent execution, transactions do not interfere with each other .
persistence (Durability): That is, once a transaction is committed , Its changes to the database are permanent . Other subsequent operations should not have any impact on its execution results .
4. Transaction isolation level
Transaction isolation level It is mainly used to solve the problems caused by the concurrent execution of transactions .
If two things are executed simultaneously or alternatively , Then their execution results may be affected by each other , This will lead to inconsistent display of data . Therefore, in order to ensure the correctness and consistency of concurrent operation data ,SQL To regulate in 1992 In, the isolation level of database transactions was proposed .
There are two main problems in transaction concurrency : The question of reading | Writing questions , As opposed to writing questions , The probability of reading problems is higher .
1. Safe hidden trouble
If the transaction has no task isolation settings , Then in the case of concurrency, the following problems will occur .
a. The question of reading
Dirty reading : It refers to that one transaction reads data that has not been committed by another transaction .
It can't be read repeatedly : One transaction reads the updated data committed by another transaction , Result in inconsistent results of multiple queries . in the light of update
Virtual reading | Slow reading : One transaction reads the inserted data committed by another transaction , Result in inconsistent results of multiple queries . in the light of insert
b. Writing questions
There is only one question written , Is to lose updates .
Lost update : Refers to a transaction to modify the database , Another transaction also modifies the database , The last thing , No matter commit or rollback, the data update of the previous transaction will be lost .
Compared with the problem of reading , The problems written are less likely to occur , There is really a lost update , Two transactions must operate on one piece of data at the same time .
terms of settlement :
1. Pessimistic locking
If you don't work, you think you'll lose updates . Query data followed by keywords for update
2. Optimism lock
Programmer control , Add a field to the table version( Version means ), The default is 0. Only one operation , This version is incremented . Next time, let's operate , Check the version number first . If it's not right , Indicates old data , You have to inquire first .
2. Isolation level
a. Read uncommitted
b. Read submitted
c. Repeatable
d. serialize | Serialization
Set read uncommitted
mysql> set session transaction isolation level read uncommitted;
Query OK, 0 rows affected (0.00 sec)
mysql> select @@transaction_isolation;
+-------------------------+
| @@transaction_isolation |
+-------------------------+
| READ-UNCOMMITTED |
+-------------------------+
1 row in set (0.00 sec)
client B Modify the account , At this point the client B The transaction has not been committed yet
client A The query , Read the client B Data not yet submitted
client B Roll back
Read uncommitted , Nothing can be solved .
Set read committed
mysql> set session transaction isolation level read committed;
Query OK, 0 rows affected (0.00 sec)
mysql> select @@transaction_isolation;
+-------------------------+
| @@transaction_isolation |
+-------------------------+
| READ-COMMITTED |
+-------------------------+
1 row in set (0.00 sec)
client B Modify :
client B Commit transaction
client A Query again
Read submitted : One transaction can read the data committed by another transaction
solve : Dirty reading
To be solved : It can't be read repeatedly , Virtual reading
Set repeatable read
mysql> set session transaction isolation level repeatable read;
Query OK, 0 rows affected (0.00 sec)
mysql> select @@transaction_isolation;
+-------------------------+
| @@transaction_isolation |
+-------------------------+
| REPEATABLE-READ |
+-------------------------+
1 row in set (0.00 sec)
client B Commit transaction :
client A Inquire about :
Virtual reading :insert operation
client B Commit transaction :
client A Query again ,MySQL The virtual reading has been solved .
https://www.jianshu.com/p/2953c64761aa mysql Avoid unreal reading
Set serialization | Serialization MySQL The highest isolation level
mysql> set session transaction isolation level serializable;
Query OK, 0 rows affected (0.00 sec)
mysql> select @@transaction_isolation;
+-------------------------+
| @@transaction_isolation |
+-------------------------+
| SERIALIZABLE |
+-------------------------+
1 row in set (0.00 sec)
client B Waiting for the client A Commit transaction , Can't wait for the client A Submit , client B Timeout will be reported . Serialization is like mutton kebabs , one by one , First, the client A, Then the client B.
client A Commit transaction :
client B Do it now :
Serialization efficiency is too low , Other things have been stuck waiting .
Sort by function size : serialize > Repeatable > Read submitted > Read uncommitted
Sort by efficiency : serialize < Repeatable < Read submitted < Read uncommitted
mysql Default isolation level : Repeatable
oracle: Read submitted
Writing questions
There is only one question written , Is to lose updates .
Lost update : Refers to a transaction to modify the database , Another transaction also modifies the database , The last thing , No matter commit or rollback, the data update of the previous transaction will be lost .
Compared with the problem of reading , The problems written are less likely to occur , Two transactions operate on one piece of data at the same time .
terms of settlement :
1. Pessimistic locking
I thought I would lose updates before I worked . Query data followed by keywords for update
client B Will be waiting for the client A, Can't wait for the client A Submission timeout , A bit like serialization
client A Do update operation :
client B Continue to wait for :
client A Commit transaction :
At this point the client B Before you can read the data :
2. Optimism lock
Programmer control , Add a field to the table version( Version means ), The default is 0. Only one operation , This version is incremented . Next time, let's operate , Check the version number first . If it's not right , Indicates old data , You have to inquire first .
边栏推荐
- JVM instruction mnemonic
- 2837xd 代码生成——StateFlow(3)
- 因上努力,果上随缘
- Idempotent design of Internet API interface
- 2837xd Code Generation - Supplement (1)
- 每天睡前30分钟阅读Day5_Map中全部Key值,全部Value值获取方式
- C语言之到底是不是太胖了
- Mathematics in machine learning -- point estimation (I): basic knowledge
- web安全与防御
- What are the differences between TP5 and laravel
猜你喜欢
2837xd Code Generation - Supplement (1)
逆变器simulink模型——处理器在环测试(PIL)
个人经历&&博客现状
2837xd 代碼生成——StateFlow(4)
分享一篇博客(水一篇博客)
Error reporting on the first day of work (incomplete awvs unloading)
Hystrix implements request consolidation
2837xd代码生成模块学习(4)——idle_task、Simulink Coder
2837xd code generation - Supplement (3)
Required request body is missing: (cross domain problem)
随机推荐
C语言之到底是不是太胖了
In depth analysis of how the JVM executes Hello World
三相逆变器离网控制——PR控制
2837xd代码生成模块学习(1)——GPIO模块
C语言之做木桶
Inverter Simulink model -- processor in the loop test (PIL)
Error reporting on the first day of work (error reporting when Nessus installs WinPcap)
C language strawberry
YOLO物体识别,生成数据用到的工具
每天睡前30分钟阅读Day5_Map中全部Key值,全部Value值获取方式
分布式锁的这三种实现方式,如何在效率和正确性之间选择?
Save video opencv:: videowriter
Read Day6 30 minutes before going to bed every day_ Day6_ Date_ Calendar_ LocalDate_ TimeStamp_ LocalTime
Pool de connexion redis personnalisé
QT qlabel style settings
How to use PHP spoole to implement millisecond scheduled tasks
C语言之数据插入
2837xd code generation - stateflow (4)
Alibaba /热门json解析开源项目 fastjson2
What is the function of laravel facade