简体   繁体   English

在MySQL中,最佳实践是将LOCK TABLES调用包装在try catch中吗?

[英]In MySQL is it best practice to wrap LOCK TABLES calls in a try catch?

执行“ LOCK TABLES”时,将调用包装在try / catch中是否明智,以确保在发生异常的情况下对表进行解锁?

In general it's a good idea to use try { } catch for operations that require undoing a previous operation in case of any errors; 通常,对于需要在发生任何错误时撤消先前操作的操作,请使用try { } catch it's not limited to just database statements. 它不仅限于数据库语句。

That said, when using databases, it's advisable to use a more granular locking mechanism such as the one that comes with transactional databases such as InnoDB. 也就是说,在使用数据库时,建议使用更细化的锁定机制,例如事务数据库(如InnoDB)随附的锁定机制。 You would still use try { } catch , but in this manner: 您仍然可以使用try { } catch ,但是采用这种方式:

// start a new transaction
$db->beginTransaction();
try {
    // do stuff
    // make the changes permament
    $db->commit();
} catch (Exception $e) {
    // roll back any changes you've made
    $db->rollback();
    throw $e;
}

The exact behaviour of conflict resolution is defined by the transaction isolation level, which can be changed to suit your needs. 解决冲突的确切行为由事务隔离级别定义,可以根据您的需要进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM