MySQL和PHP:使用SELECT FOR UPDATE

时间:2017-03-02 20:30:25

标签: php mysql locking

我正在尝试为数据库中的表获取行级锁定,以防止任何将来的会话在释放锁之前读取该行。

为了实现这一点,我一直在尝试在索引列上使用With Member [Measures].[MeasureY] as IIF( IsEmpty([Measures].[MeasureX]), Null, [Date].[Year].CurrentMember.Properties("Member_Value") * 100000000000 + [Measures].[MeasureX] ) SELECT NON EMPTY { [Measures].[MeasureX] } ON COLUMNS, NON EMPTY { TopCount( Generate( [Person].[Country].[Country].Members, TopCount( [Date].[Year].[Year].Members, 1, [Measures].[MeasureY] ) ), 10, [Measures].[MeasureY] ) } ON ROWS FROM [Cube] 语法,但我似乎无法阻止其他会话在使用完全相同的查询时读取该行。

我还需要做些什么吗?我正在使用MySQL 5.5,PHP 7,并且该表是Innodb。

详细说明,流程是:

SELECT ... FOR UPDATE

后续请求也将运行完全相同的代码行,但我希望一个请求阻止其他请求启动,直到它提交事务为止。

2 个答案:

答案 0 :(得分:0)

您是否查看了有关InnoDB锁类型的MySql文档?

https://dev.mysql.com/doc/refman/5.5/en/innodb-locking.html

答案 1 :(得分:0)

由于某些未知的原因,我无法使SELECT FOR UPDATE与我的代码一起正常工作(尽管仍在尝试),但与此同时,我不得不在innoDB表上实现自己的锁。问题是要避免我正在开发的支付网关的交易余额混淆。以下伪代码可以帮助正在寻找备用交易锁的任何人。

//Add transaction lock flag column into your table
//TXN_LOCK; Defaulted to Integer 0;

//FIRST: Select the balance and current txn-lock value  
$stopCount = 1;
$dbBalance = $tnxLock = 0;
$failureFlag = false; 
do {
    //run the select query; get values including $dbBalance and $tnxLock 
    //increment the counter; we won't run this forever          
    $stopCount++;
    if($stopCount > 3){
        //only a few trials
        $failureFlag = true;
        break;
    }
    //lock table, it looks free
    if($tnxLock == '0'){
        //update table set tnxLock = 1;         
    }
}while ($tnxLock > 0);  

if($failureFlag){
    //log and end; return failure   
    return false;
}else {
    //proceed 
}   
//--------------------------------

//now do you mathematics 
//add or subtract value from the balance

//then update the table; at the same time update the lock-code back to zero 
//UPDATE table set balance = xxx, tnxLock = 0;

//NOTE: This can be set as a function, 
//   with right params and flags of doing both credits and debits and 
//   called each time such operation is needed for consistency
//   Normal begin and commit transaction can also be added for more stability