DaLei@home:~$

MySQL事务等级相关实验



查看事务等级

  • 查看全局事务等级和当前会话等级
    SELECT @@global.tx_isolation,@@tx_isolation;
    REPEATABLE-READ  REPEATABLE-READ
    #MySQL 默认事务等级是这两种
  • 修改全局事务等级和当前会话等级
    # 全局
    set global transaction isolation level serializable;
    # 会话
     set session transaction isolation level serializable;

基于RR事务等级的实验

  • 初始化工作-创建表
    create  table test_wl (id int PRIMARY KEY AUTO_INCREMENT, name varchar(20), num int);
  • 一般的更新操作,按照给定的编号执行
    # session1: 会话一
    1. start transaction;
    4. update test_wl set num = 40 where id = 1;
    6. commit;

    # session2: 会话二
    2. start transaction;
    3. update test_wl set num = 20 where id = 1;
    5. commit;

第4步会等待第5步执行完成才会执行,并且

第4步会覆盖操作的值

  • 更新操作,判断select是否会自动加锁
    # session1: 会话一
    1. start transaction;
    3. select * from test_wl where id=1;
    5. update test_wl set num = 40 where id = 1;
    7. commit;

    # session2: 会话二
    2. start transaction;
    4. update test_wl set num = 20 where id = 1;
    6. commit;

第5步在第6步后执行,并且覆盖值为40

第5步会覆盖操作的值,select操作并不会加锁

  • 更新操作,select操作手动加锁
    # session1: 会话一
    1. start transaction;
    3. select * from test_wl where id=1 for update;
    5. update test_wl set num = 20 where id = 1;
    6. commit;

    # session2: 会话二
    2. start transaction;
    4. update test_wl set num = 30 where id = 1;
    7. commit;

第4步会等待第6步执行完成才会执行

第4步会覆盖操作的值

基于Serializable事务等级的实验

  • 更新操作,select操作自动加行锁
    # session1: 会话一
    1. set session transaction isolation level serializable; 
    3. start transaction;
    5. select * from test_wl where id=1;
    7. update test_wl set num = 30 where id = 1;
    8. commit;

    # session2: 会话二
    2. set session transaction isolation level serializable; 
    4. start transaction;
    6. update test_wl set num = 20 where id = 1;
    9. commit;

session1会成功更改值 session2会报死锁的错

  • 更新操作,select操作自动加行锁,并不会影响其他行更新操作
    # session1: 会话一
    1. set session transaction isolation level serializable; 
    3. start transaction;
    5. select * from test_wl where id=1;
    7. update test_wl set num = 40 where id = 1;
    8. commit;

    # session2: 会话二
    2. set session transaction isolation level serializable; 
    4. start transaction;
    6. update test_wl set num = 20 where id = 2;
    9. commit;

session1和session2会成功更改值