第十八周-6.29-## 自增自减操作,事务


## 自增自减操作

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)等待


幻读
脏读


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值