php 用php锁定mysql表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12179290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lock mysql table with php
提问by pain.reign
Script 1.
脚本 1.
$query_ = "lock tables test1 as test11 write";
mysql_query($query);
$query_ = "select * from test11";
sleep(20);
$query_ = "unlock tables";
mysql_query($query_);
Script 2.
脚本 2。
$query_ = "select * from test1";
$result = mysql_query($query_);
The problem is that if i run second script while running first script. Table is notlocked. And i can read any data from it.
问题是,如果我在运行第一个脚本时运行第二个脚本。表未锁定。我可以从中读取任何数据。
I need it to be locked and return error.
我需要它被锁定并返回错误。
How to make this work?
如何使这项工作?
采纳答案by Fluffeh
You are readlocking the table with $query_ = "lock tables test1 as test11 read";- which means that other queries can still read it without any problems what-so-ever (Relevant link- scroll down to the section on lock types):
您正在read锁定表$query_ = "lock tables test1 as test11 read";- 这意味着其他查询仍然可以毫无问题地读取它(相关链接- 向下滚动到锁定类型部分):
Info on the readlock type:
关于read锁类型的信息:
- The session that holds the lock can read the table (but not write it).
- Multiple sessions can acquire a READ lock for the table at the same time.
- Other sessions can read the table without explicitly acquiring a READ lock.
- 持有锁的会话可以读取表(但不能写入)。
- 多个会话可以同时获取表的 READ 锁。
- 其他会话无需显式获取 READ 锁即可读取该表。
If you want to stop anythingelse so much as reding the table, you need to use a writelock as follows:
如果你想停止任何其他事情,比如红表,你需要使用一个write锁,如下所示:
$query_ = "lock tables test1 as test11 write";
回答by jsist
If you do not want others to access that table then use
如果您不希望其他人访问该表,请使用
LOCK TABLES test1 WRITE;
Other script will not return error but will wait until lock is released.
其他脚本不会返回错误,而是会等到锁定被释放。
Hope it helps...
希望能帮助到你...
回答by Louis Tang
You have to grant the rights of lock tables to the db user.
您必须将锁定表的权限授予 db 用户。
回答by still_dreaming_1
You have a misconception about what locks do. Locks to do not prevent other scripts from accessing data, instead locks affect the timing of when other scripts will access the data. When script 2 tries to access or modify data that it is not allowed to because of a lock, it will pause and wait for the lock to be released. After script 1 unlocks the table, script 2 will proceed and complete without any problems.
你对锁的作用有误解。锁不会阻止其他脚本访问数据,而是会影响其他脚本访问数据的时间。当脚本 2 尝试访问或修改由于锁定而不允许访问的数据时,它将暂停并等待锁定被释放。脚本 1 解锁表后,脚本 2 将继续并完成,没有任何问题。

