Can we lock tables while executing a query in Zend-Db

ぐ巨炮叔叔 提交于 2020-02-23 04:35:06

问题


I am talking about doing something like this:

LOCK TABLE page WRITE;

SELECT * FROM page WHERE col = 'value';

INSERT INTO page(col1, col2) VALUES('val1', val2);

UNLOCK TABLES;


回答1:


I don't see an actual Zend DB method to lock tables, but maybe just do this:

//Lock Table
$sql = "LOCK TABLE page WRITE";
$db->fetchRow($sql);

//Get your data
$sql = "SELECT * FROM page WHERE col='value'";
$result = $db->fetchAll($sql);

//Make the insert
$data = array( 'col1' => 'val1', 'col2' => 'val2' );
$db->insert('page', $data);

//Unlock tables
$sql = "UNLOCK TABLES";
$db->fetchRow($sql);

Probably not the best solution and it's untested. But it might work for ya.

UPDATE: I have come across a better solution for you. Use transactions:

// Start a transaction explicitly.
$db->beginTransaction();

try {
    //Get your data
    $sql = "SELECT * FROM page WHERE col='value'";
    $result = $db->fetchAll($sql);
    //Make the insert
    $data = array( 'col1' => 'val1', 'col2' => 'val2' );
    $db->insert('page', $data);

    // If all succeed, commit the transaction and all changes
    // are committed at once.
    $db->commit();

} catch (Exception $e) {
    // If any of the queries failed and threw an exception,
    // we want to roll back the whole transaction, reversing
    // changes made in the transaction, even those that succeeded.
    // Thus all changes are committed together, or none are.
    $db->rollBack();
    echo $e->getMessage();
}

I have recently come across the same problem and transactions have worked great. Definitely the way to go.




回答2:


Zend_Db transactions do not guarantee locks! See this on how to make proper isolated transactions.

Database transactions in Zend Framework: Are they isolated?




回答3:


$this->_db->getConnection()->exec('LOCK TABLES page');




回答4:


I think you would need to use an adapter, I'm not sure locking works though.

$model->getAdapter()->query($sql, $bind);



来源:https://stackoverflow.com/questions/1593895/can-we-lock-tables-while-executing-a-query-in-zend-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!