什么是事务
事务就是操作多条sql语句,这些sql语句必须要同时执行成功,如果有一个执行失败,那么他就回到原来的状态
事务的作用
保证数据的安全性,如果银行之间的转账操作
事务的4个特性 ACID
原子性 atomicity :
事务包含的所有操作要么全部成功,要么全部失败回滚;成功必须要完全应用到数据库,失败则不能对数据库产生影响
一致性 consistency :
事务执行前和执行后必须处于一致性的状态,例如 张三和王八一共有500大洋,无论他们之间如何相互的转账的,在他们转完帐之后,也就是事务结束之后,他们的钱加起来还是500大洋,这就是事务的一致性
隔离性 isolation :
当多个用户并发访问数据库时,数据库为每一个用户开启的事务,不被其他事务的操作所干扰,多个并发事务之间要相互隔离
持久性 durability :
一个事务一旦被提交了,那么对数据库中的数据的改变就是永久性的,即便在数据库系统遇到故障的情况下也不会丢失事物的操作
如何用事务
create table user(
id int primary key auto_increment,
name char(32),
balance int
);
insert into user(name,balance)
values
('wsb',1000),
('egon',1000),
('ysb',1000);
# 修改数据之前先开启事务操作
start transaction;
# 修改操作
update user set balance=900 where name='wsb'; #买支付100元
update user set balance=1010 where name='egon'; #中介拿走10元
update user set balance=1090 where name='ysb'; #卖家拿到90元
# 回滚到上一个状态
rollback;
# 查询表中的数据看一下
select * from user;
mysql> select * from user;
+----+------+---------+
| id | name | balance |
+----+------+---------+
| 1 | wsb | 1000 |
| 2 | egon | 1000 |
| 3 | ysb | 1000 |
+----+------+---------+
3 rows in set (0.00 sec)
从这里可以看出来,之前更新的数据根本就没有被修改。为啥呢?
只要事务没有别提交,数据还是在内存中,提交之后才会保存到硬盘中
# 修改数据之前先开启事务操作
start transaction;
# 修改操作
update user set balance=900 where name='wsb'; #买支付100元
update user set balance=1010 where name='egon'; #中介拿走10元
update user set balance=1090 where name='ysb'; #卖家拿到90元
# 提交事务
commit;
# 回滚到上一个状态
rollback;
# 查询表中的数据看一下
select * from user;
mysql> select * from user;
+----+------+---------+
| id | name | balance |
+----+------+---------+
| 1 | wsb | 900 |
| 2 | egon | 1010 |
| 3 | ysb | 1090 |
+----+------+---------+
3 rows in set (0.00 sec)
so 修改了吧
从代码的角度来搞一下
try:
update user set balance=900 where name='wsb'; #买支付100元
update user set balance=1010 where name='egon'; #中介拿走10元
update user set balance=1090 where name='ysb'; #卖家拿到90元
except Exception as e:
rollback;
else:
commit;
ok ,
本文介绍了MySQL事务,事务是操作多条SQL语句,需同时执行成功,若有一个失败则回滚。其作用是保证数据安全,如银行转账。事务有ACID四个特性,还说明了事务未提交时数据在内存,提交后保存到硬盘,并提及从代码角度操作事务。
23万+

被折叠的 条评论
为什么被折叠?



