Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีล็อกหลายตารางพร้อมกันใน MySQL

ใช้คำสั่ง LOCK TABLES เพื่อล็อกหลายตาราง ไวยากรณ์:

LOCK TABLES yourTableName1 WRITE; LOCK TABLES yourTableName2 WRITE; LOCK TABLES yourTableName3 WRITE; ...

การล็อกตารางไม่ปลอดภัยต่อธุรกรรม (transaction-safe) จะ commit ธุรกรรมที่ทำงานอยู่ก่อน แล้วค่อยพยายามล็อกตารางถัดไป

สมมติมีตาราง 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 (ซึ่งมีอยู่แล้ว):

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)

ตอนนี้ตารางถูกล็อกสำหรับ session นี้ หากพยายามสร้างตารางใหม่จะ error:

mysql> create table LockTableDemo ( UserId int, UserName varchar(10) ); ERROR 1100 (HY000): Table 'LockTableDemo' was not locked with LOCK TABLES

แก้ไขโดย restart MySQL