事务
事务就是一组原子性的sql查询,或者说一个独立的工作单位。
也就是说事务内的语句,要么执行成功,要么执行
事务特性:ACID
特性 | 定义 |
---|---|
原子性Atomicity | 一个事务必须被视为一个不可分割的最小工作单位,是个事务中的所有操作要么全部提交成功,要么全部失败回滚,对于一个事务来说,不可能只执行其中的一部分操作 |
一致性Consistency | 事务在执行前数据库的状态与执行后数据库的状态保持一致 |
隔离性Isolation | 一个事务所作的修改在最终的提交之前,对其他事务是不可见的,事务与事务之间,执行时保持隔离的状态 |
持久性Durability | 一旦事务提交,则其所做的修改就会永久的保存到数据库中 |
并发产生的问题
name | 隔离级别 |
---|---|
脏读 | 事务可以读取未提交的数据 |
不可重复读 | 一个事务两次读取的数据内容不一致 |
幻读 | 指的是当某个事务在读取某个范围的记录时,另一个事务又在该范围插入了新的数据,一个事务两次读取的数据量不一致 |
隔离级别
name | 隔离级别 | 脏读 | 不可重复读 | 幻读 |
---|---|---|---|---|
读未提交 | read uncommitted | yes | yes | yes |
读已提交 | read committed | no | yes | yes |
可重复读 | repeatable read | no | no | yes |
串行化 | serializable | no | no | no |
注:
- 查看数据库默认级别:
select @@tx_isolation;
set global transaction isolation level 级别字符串;
- 查看是否自动提交:
show variables like 'autocommit';
set autocommit=1; start transaction; sql语句 commit;
死锁是指两个或多个事务在同一资源上互相占用,并请求锁定对方占用的资源,从而导致恶行循环的现象;
事务1:
start transaction;
update table_name set name='hh' where id='1';
update table_name set name='tt' where id='2';
commit;
start transaction;
update table_name set name='hh' where id='2';
update table_name set name='tt' where id='1';
commit;
InnoDB处理死锁的方法是:将持有最少行级排它锁的事务进行回滚;