开发者

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

开发者 https://www.devze.com 2022-12-08 19:02 出处:网络
I am talking about doing something like this: LOCK TABLE page WRITE; SELECT * FROM pag开发者_StackOverflow中文版e WHERE col = \'value\';

I am talking about doing something like this:

LOCK TABLE page WRITE;

SELECT * FROM pag开发者_StackOverflow中文版e WHERE col = 'value';

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

UNLOCK TABLES;


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.


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

Database transactions in Zend Framework: Are they isolated?


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


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消