文章目录
- 一、什么是事务控制
- 二、事务的四个特性
- 三、MySQL的事务控制
一、什么是事务控制
二、事务的四个特性
三、MySQL的事务控制
- 在默认情况下,MySQL是自动提交事务的,即每一条
INSERT
、UPDATE
、DELETE
的SQL语句提交后会立即执行COMMIT
操作(每条操作都当成一个事务)。因此,要开启一个事务,可以使用start transaction
或begin
,或者将autocommit
的值设置为0
1. 语法
select @@autocommit;
show variables like "autocommit";
begin;
start transaction;
rollback;
commit
set autocommit=0;
set autocommit=1;
2. 事务的两种使用方式
3. 示例
-
先准备数据
create table bank_account(id int not null auto_increment primary key,name varchar(30) comment 'name',balance decimal(18,2) comment '账户余额'
)ENGINE=InnoDB;insert into bank_account(id,name,balance) values(1,'张三',0);
insert into bank_account(id,name,balance) values(2,'李四',0);update bank_account set balance = balance+1000 where id=1;
mysql> select * from bank_account;
+
| id | name | balance |
+
| 1 | 张三 | 1000.00 |
| 2 | 李四 | 0.00 |
+
2 rows in set (0.00 sec)
-
现在不用事务,自动提交进行操作:张三给李四转100
mysql> select @@autocommit;
+
| @@autocommit |
+
| 1 |
+
1 row in set (0.00 sec)
mysql> update bank_account set balance = balance-100 where name='张三';
Query OK, 1 row affected (0.00 sec)
Rows matched:1 Changed: 1 Warnings: 0
mysql> update bank_account set balance = balance+100 where name='李';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
mysql> select * from bank_account;
+
| id | name | balance |
+
| 1 | 张三 | 900.00 |
| 2 | 李四 | 0.00 |
+
2 rows in set (0.00 sec)
-
下面用事务的方式,注意关闭自动提交
mysql> select * from bank_account;
+
| id | name | balance |
+
| 1 | 张三 | 1000.00 |
| 2 | 李四 | 0.00 |
+
2 rows in set (0.00 sec)
mysql> set autocommit=0;
Query OK, 0 rows affected (0.00 sec)
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)
mysql> update bank_account set balance = balance-100 where name='张三';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update bank_account set balance = balance+100 where name='李四';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> commit;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from bank_account;
+
| id | name | balance |
+
| 1 | 张三 | 900.00 |
| 2 | 李四 | 100.00 |
+
2 rows in set (0.00 sec)
-
试一下回滚
mysql> update bank_account set balance = 1000 where name='张三';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
mysql> commit;
Query OK, 0 rows affected (0.12 sec)
mysql> update bank_account set balance = balance-100 where name='张三';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> rollback;
Query OK, 0 rows affected (0.13 sec)
mysql> select * from bank_account;
+
| id | name | balance |
+
| 1 | 张三 | 1000.00 |
| 2 | 李四 | 0.00 |
+
2 rows in set (0.00 sec)