借助 LOCK TABLES 命令,您可以实现多个表锁。语法如下 -
LOCK TABLES yourTableName1 WRITE;
LOCK TABLES yourTableName2 WRITE;
LOCK TABLES yourTableName3 WRITE;
LOCK TABLES yourTableName4 WRITE;
.
.
.
N;
表锁不是事务安全的,它在尝试锁定第二个表之前首先隐式提交活动事务。
假设我有一个表 OrderDemo -
mysql> create table OrderDemo
-> (
-> OrderId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> OrderPrice int,
-> OrderDatetime datetime
-> );
Query OK, 0 rows affected (0.66 sec)
这里是锁定表 OrderDemo 和 utfdemo 的查询。 utfdemo 已存在于示例数据库中。查询如下 -
mysql> LOCK TABLES OrderDemo WRITE;
Query OK, 0 rows affected (0.03 sec)
mysql> LOCK TABLES utfdemo WRITE;
Query OK, 0 rows affected (0.07 sec)
现在它锁定会话的表。如果您尝试创建表格,则会收到错误。
错误如下 -
mysql> create table LockTableDemo
-> (
-> UserId int,
-> UserName varchar(10)
-> );
ERROR 1100 (HY000): Table 'LockTableDemo' was not locked with LOCK TABLES
mysql> create table UserIformation
-> (
-> UserId int,
-> UserName varchar(10)
-> );
ERROR 1100 (HY000): Table 'UserIformation' was not locked with LOCK TABLES
要解决此问题,您需要重新启动 MySQL。