如何在MySQL中锁定多个表?
您可以借助LOCKTABLES命令获得多个表锁。语法如下-
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 -> );
这是锁定表OrderDemo和utfdemo的查询。utfdemo已存在于示例数据库中。查询如下-
mysql> LOCK TABLES OrderDemo WRITE; mysql> LOCK TABLES utfdemo WRITE;
现在,它锁定了会话表。如果尝试创建表,则会出现错误。
错误如下-
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。