[英]How to prevent concurrency issue with database update?
I have the following sequence which may be executed by more than one instance of my program at any time: 我有以下序列,可以随时由我的程序的多个实例执行:
Step 1: Check to see whether bill is unpaid
步骤1:检查帐单是否未付款
Step 2: If bill is unpaid, then mark bill as paid
步骤2:如果未付帐单,则将帐单标记为已付
I am worried that Instance 1 and Instance 2 of my program will both do Step 1 at almost exactly the same time and therefore proceed to both do Step 2. How can I prevent this happening? 我担心我的程序的实例1和实例2几乎都同时执行步骤1,因此都继续执行步骤2。如何防止这种情况发生?
Using a (serializable) TRANSACTION
. 使用(可序列化的)
TRANSACTION
。 More details depend on your database platform 更多详细信息取决于您的数据库平台
See http://en.wikipedia.org/wiki/Database_transaction for details 有关详细信息,请参见http://en.wikipedia.org/wiki/Database_transaction
It's hard to be concrete about this without seeing code, but the obvious way to do this is to combine steps 1 and 2. 不看代码就很难具体说明这一点,但是显而易见的方法是将步骤1和2结合起来。
So, instead of: 因此,代替:
$invoice_status = call_database(
select INVOICE_STATUS
from INVOICES
where INVOICE_ID = $invoice_id)
if ($invoice_status = UNPAID){
call_database (
UPDATE INVOICES
SET INVOICE_STATUS = PAID
WHERE INVOICE_ID = $invoice_id)
}
You would do something like 你会做类似的事情
call_database(
update invoices
set invoice_status = PAID
where invoice_id = $invoice_id
and invoice_status = UNPAID)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.