## 自增自减操作
create database gzsp;
use gzsp;
```
create table stu(
id int,
user_name varchar(50),
money double
)engine=InnoDB;
```
```
insert into stu values
(1, "本本", 1000),
(2, "静静", 1200);
```
静静 充值 500
1. 先查询
select * from stu where user_name ="静静";
2. 再添加
update stu set money=1700 where id = 2;
select * from stu where id = 2;
一步完成: 本本 充值 400
update stu set money=money+400 where user_name ="本本";
select * from stu where user_name ="本本";
意外: 消费的情况下
消费 800
update stu set money=money-800 where user_name ="本本";
select * from stu where user_name ="本本";
update stu set money=money-800 where user_name ="本本";
select * from stu where user_name ="本本";
## 事务
原子、 一致性
原子: 最小单位,一般情况下, 一条 SQL 语句
应用场景
1. 静静 转账给 本本 1000元
1. 查询静静余额 1700
2. 静静 -1000
3. 本本 + 1000
1. 开启事务 start transaction;
2. 操作 (多条SQL语句操作)
3. 提交事务 commit;
回滚事务 rollback;
start transaction;
select * from stu where user_name ="静静";
update stu set money=money-1000 where user_name ="静静";
update stu set money=money+1000 where user_name ="本本";
commit;
+------+-----------+-------+
| id | user_name | money |
+------+-----------+-------+
| 1 | 本本 | -1600 |
| 2 | 静静 | 700 |
+------+-----------+-------+
回滚操作
start transaction;
select * from stu where user_name ="静静";
update stu set money=money-500 where user_name ="静静";
update stu set money=money+500 where user_name ="本本";
select * from stu;
+------+-----------+-------+
| id | user_name | money |
+------+-----------+-------+
| 1 | 本本 | -1100 |
| 2 | 静静 | 200 |
+------+-----------+-------+
rollback;
select * from stu;
## 锁
死锁(高并发): 超时(3s)等待
幻读
脏读