zoukankan      html  css  js  c++  java
  • mysql行锁和表锁

     

    在调用存储过程中,就会涉及到表锁,行锁这一概念:所谓区别:有索引的时候就是行锁,没有索引的时候就是表索。

    innodb 的行锁是在有索引的情况下,没有索引的表是锁定全表的.

    表锁演示(无索引)

    Session1:

    mysql> set autocommit=0;

    mysql> select * from innodb_test;
    +------+-------------+
    | id   | name        |
    +------+-------------+
    |    1 | woshiceshi  | 
    |    2 | woshiceshi2 | 
    |    3 | woshiceshi3 | 
    +------+-------------+

    mysql> select * from innodb_test where id = 2 for update;
    +------+------------+
    | id   | name       |
    +------+------------+
    |    2 | woshiceshi2 | 
    +------+------------+

    Session2:

    mysql> update innodb_test set name='sjis' where id = 1 ;
    处于等待状态....

    再回到session1 commit以后,session2就出来结果了(锁定了8秒,过了8秒左右才去session1提交)。

    mysql> update innodb_test set name='sjis' where id = 1 ;
    Query OK, 1 row affected (8.11 sec)
    Rows matched: 1  Changed: 1  Warnings: 0

    实验结果是:我在session1的for update 操作看似只锁定ID为2的行其实锁定了全表,以至于后面session2的对ID为1的行update 需要等待Session1锁的释放。

    行锁演示(索引为ID)

    Session1:
    mysql> alter table innodb_test add index idx_id(id);
    Query OK, 4 rows affected (0.01 sec)
    Records: 4  Duplicates: 0  Warnings: 0

    mysql> select * from innodb_test where id = 2 for update;
    +------+------------+
    | id   | name       |
    +------+------------+
    |    2 | woshiceshi2 | 
    +------+------------+

    Session2:

    mysql> update innodb_test set name='wohaishiceshi' where id = 1 ;
    Query OK, 1 row affected (0.02 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    mysql> select * from innodb_test where id = 1;           
    +------+---------------+
    | id   | name          |
    +------+---------------+
    |    1 | wohaishiceshi | 
    +------+---------------+
    1 row in set (0.00 sec)

    实验结果:这次的锁定是锁定的行,所以没有被锁定的行(ID不为2的行)可以进行update..

    http://keshion.iteye.com/category/125242

  • 相关阅读:
    设计模式(十):享元模式
    设计模式(九):装饰者模式
    设计模式(八):组合模式
    设计模式(七):桥接模式
    设计模式(六):适配器模式
    设计模式(一)工厂模式(补) -- 理解记忆方式
    [转] 本地项目上传github (新项目 / 旧项目)
    设计模式(五):外观模式
    php语言搭建nginx反向代理,负载均衡常遇到的问题
    linux tail命令用法
  • 原文地址:https://www.cnblogs.com/architects/p/4325406.html
Copyright © 2011-2022 走看看