Board logo

标题: mysql锁表案例 [打印本页]

作者: fangzhen    时间: 2010-9-25 18:23     标题: mysql锁表案例

在进行数据表SelectUpdateInsert时,可以先将数据表锁定,来实现对某一时间点多个表的一致性读取。
mysql> lock tables ip read;   
#表示要锁定成只读状态,在这个状态下用户只能读取数据表,不能写入。         
mysql> lock tables ip read local;   
#local选项表示当前用户只能读取,其他用户可以在表尾插入记录。
mysql>FLUSH TABLES;
mysql> unlock tables;   #解除锁定
 
mysql> lock tables ip read local;
Query OK, 0 rows affected (0.00 sec)
 
mysql> insert into ip values(member,192.168.0.11,20091018);
ERROR 1099 (HY000): Table ip was locked with a READ lock and cant be updated
 
mysql> unlock tables;
Query OK, 0 rows affected (0.01 sec)
 
多表锁定
mysql> lock table user as a read, ip as b read, state as c read;
Query OK, 0 rows affected (0.00 sec)
 
mysql> select a.user_name,a.user_pass,b.user_ip,visi_date,c.value
    -> from user a,ip b,state c
    -> where a.user_name=share and b.user_ip=172.16.0.33
    -> and a.user_name=b.user_name
    -> and a.user_state=c.stat;
+-----------+-----------+-------------+------------+-------+
| user_name | user_pass | user_ip     | visi_date  | value |
+-----------+-----------+-------------+------------+-------+
| share     | 111111    | 172.16.0.33 | 0000-00-00 | 正常  |
+-----------+-----------+-------------+------------+-------+
1 row in set (0.01 sec)。
 
可以通过检查table_locks_waitedtable_locks_immediate状态变量来分析系统上的表锁定争夺。
mysql> show status like table%;
+-----------------------+-------+
| Variable_name         | Value |
+-----------------------+-------+
| Table_locks_immediate | 27    |
| Table_locks_waited    | 0     |
+-----------------------+-------+
2 rows in set (0.00 sec)





欢迎光临 PHP开发笔记 (http://phpvi.com/) Powered by Discuz! 6.1.0