#首先设置mysql1和mysql2隔离级别为read uncommited set session transaction isolation level read uncommitted; #禁用mysql1 mysql2的自动提交 set autocommit = 0; update users set u_name='李四' where id = 3;#① mysql1修改数据但未提交 select * from users where id =3;#② mysql1 查询数据 为李四 select * from users where id =3;#③ mysql2 查询数据 也为李四 查询到了mysql1中未提交的数据 出现了脏读 insert into users (u_name) values ('刘亦菲');#④mysql1 插入数据但未提交 select * from users where u_name = '刘亦菲';#⑤mysql1 查询到该数据 select * from users where u_name = '刘亦菲';#⑥mysql2 查询到该数据 出现了幻读
#首先设置mysql1和mysql2隔离级别为read commited set session transaction isolation level read committed; #禁用mysql1 mysql2的自动提交 set autocommit = 0; update users set u_name='李四' where id = 3;#① mysql1修改数据但未提交 select * from users where id =3;#② mysql1 查询数据 为李四 select * from users where id =3;#③ mysql2 查询数据 为张三0 没有出现脏读 insert into users (u_name) values ('刘亦菲');#④mysql1 插入数据但未提交 select * from users where u_name = '刘亦菲';#⑤mysql1 查询到该数据 select * from users where u_name = '刘亦菲';#⑥mysql2 没有查询到该数据
#首先设置mysql1和mysql2隔离级别为repeatable read set session transaction isolation level repeatable read; #禁用mysql1 mysql2的自动提交 set autocommit = 0; update users set u_name='李四' where id = 3;#① mysql1修改数据但未提交 select * from users where id =3;#② mysql1 查询数据 为李四 select * from users where id =3;#③ mysql2 查询数据 为张三0 没有出现脏读 insert into users (u_name) values ('刘亦菲');#④mysql1 插入数据但未提交 select * from users where u_name = '刘亦菲';#⑤mysql1 查询到该数据 select * from users where u_name = '刘亦菲';#⑥mysql2 没有查询到该数据
commit;#⑦mysql1 提交之前的操作 此时mysql2还是没有数据
幻读演示
mysql在某种情况下可以去除幻读,在使用间隙锁的时候可以避免幻读
在事务1中执行
1
update staff set age = age+1whereid < 10andid > 1;