如何防止数据库更新的并发问题? [英] How to prevent concurrency issue with database update?

查看:418
本文介绍了如何防止数据库更新的并发问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下序列,可以在任何时候由我的程序的多个实例执行:


1:检查帐单是否未付款



步骤2:如果帐单未付, p>

我担心我的程序的实例1和实例2将几乎完全同时执行步骤1,因此继续执行步骤2.如何防止这种情况?

解决方案

 

code> $ invoice_status = call_database(
select INVOICE_STATUS
从INVOICES
其中INVOICE_ID = $ invoice_id)

if($ invoice_status = UNPAID){
call_database(
UPDATE INVOICES
SET INVoICE_STATUS = PAID
WHERE INVOICE_ID = $ invoice_id)
}

您将执行

  call_database(
update invoices
set invoice_status = PAID
其中invoice_id = $ invoice_id
和invoice_status = UNPAID)


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

Step 2: If bill is unpaid, then mark bill as paid

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?

解决方案

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.

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)

这篇关于如何防止数据库更新的并发问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆