Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock table for reading and writing

Tags:

php

mysql

How to lock table for reading and writing with php? Here is what I tried without luck.

mysql_query("LOCK TABLES table WRITE;");
mysql_query("LOCK TABLES table READ, WRITE;");
mysql_query("LOCK TABLES table READ WRITE;");

Here is the error I got:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WRITE' at line 1

like image 995
user1014152 Avatar asked Nov 02 '11 14:11

user1014152


People also ask

What is the use of lock table?

A locked table remains locked until you either commit your transaction or roll it back, either entirely or to a savepoint before you locked the table. A lock never prevents other users from querying the table. A query never places a lock on a table. Readers never block writers and writers never block readers.

How do you lock a table explicitly?

The following is the syntax that allows us to acquire a table lock explicitly: LOCK TABLES table_name [READ | WRITE];

Which lock is used on read lock?

1. Shared Lock (S): Another transaction that tries to read the same data is permitted to read, but a transaction that tries to update the data will be prevented from doing so until the shared lock is released. Shared lock is also called read lock, used for reading data items only.

How does MySQL read locks and write locks?

The MySQL locks are taken at the same time as those acquired explicitly with the LOCK TABLES statement. If a table is locked explicitly for reading with LOCK TABLES but needs to be locked for writing since it might be modified within a trigger, a write lock might be taken instead of a read lock.


1 Answers

mysql_query("LOCK TABLE table WRITE"); // you might think it's here
mysql_query("LOCK TABLE table READ, table AS t2 WRITE"); // <- but the error is here
mysql_query("LOCK TABLES table READ, table as t2 WRITE"); // <- ...and here.

You can not acquire multiple locks for the same table without aliasing it. Read the manual.

like image 129
Shef Avatar answered Oct 13 '22 11:10

Shef