事务是一组具有原子性的SQL语句,或是一个独立的工作单元
一致性,原子性,隔离性,持久性 ---- ACID
select @@tx_isolation; //查询当前的隔离级别
set session transaction isolation level read uncommitted/read committed/repeatable read/serializable //设置隔离级别
set autocommit = on/off; //事务的自动提交
当数据库上有多个事务同时执行的时候,就有可能出现脏读(dirty read)、不可重复读、幻读的问题,隔离级别就是用来解决这个问题
级别名称 | 脏读 | 不可重复读 | 幻读 | 值 |
---|---|---|---|---|
读未提交 | 是 | 是 | 是 | 0 |
读提交 | 否 | 是 | 是 | 1 |
可重复读 | 否 | 否 | 是 | 2 |
串行化 | 否 | 否 | 否 | 3 |
A客户端设置read uncommitted
事务A | 事务B |
---|---|
begin | begin |
insert into s_users values(2,‘demo‘,2000); | |
select * from s_users where id = 2; (能查询到id=2的数据) | |
rollback; | |
select * from s_users where id = 2; (为空) | |
select * from s_users where id = 2; (为空) |
将客户端A的隔离级别设置为read committed
事务A | 事务B |
---|---|
begin | beigin |
update s_users set money=0 where id = 1; | |
select * from s_users where id = 1; (查询到money:1000) | |
commit; | |
select * from s_users where id = 1; (查询到money:0) |
将客户端A的隔离级别设置为 repeatable read
事务A | 事务B | 事务C |
---|---|---|
start transaction with consistent snapshot | ||
start transaction with consistent snapshot | ||
update s_users set money = money + 800 where id = 1 (money=1800) | ||
update s_users set money = money + 200 where id = 1 (money=2000) | ||
select * from s_users where id =1 (1000) | ||
commit | ||
select * from s_users where id =1 (1000) | ||
commit |
select * from s_users for update;
来保证其它的事务无法来调用。在innodb中锁的都是索引,而非记录本身。原文:https://www.cnblogs.com/Daneil/p/13823972.html