如何在MySQL中锁定多个表?
mysqlmysqli database
您可以使用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。