gpt4 book ai didi

php - 查询时临时锁定MYSQL表?

转载 作者:行者123 更新时间:2023-11-29 23:24:12 25 4
gpt4 key购买 nike

我对使用数据库非常陌生。我目前正在使用 Google Cloud SQL 并通过 PHP PDO 访问数据库。

我设法找到一个网站( http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ),其中包含一些示例代码:

<?php
try {
$db->beginTransaction(); //<---- 1

$db->exec("SOME QUERY"); //<---- 2

$stmt = $db->prepare("SOME OTHER QUERY?");
$stmt->execute(array($value));

$stmt = $db->prepare("YET ANOTHER QUERY??");
$stmt->execute(array($value2, $value3));

$db->commit(); //<---- 3
} catch(PDOException $ex) {
//Something went wrong rollback!
$db->rollBack();
echo $ex->getMessage();
}

根据上面的代码,如果我执行“$db->beginTransaction();”,是否会开始锁定表?然后 '$db->e​​xec("SOME QUERY");'会像平常一样。最后,'$db->commit();'会保存上面的所有内容并解锁 table 吗?

如果一切都正确运行,那么我是否应该假设当第 2 行正在运行时,无法完成对表的其他调用(它们将排队),并且只有在调用此处的第 3 行后才能开始其他调用?我只是想知道我对这个过程(以及代码是如何编写的)的理解是否准确。

最佳答案

首先,由于您使用的是 try/catch,因此您需要确保 PDO 的错误模式是异常:http://php.net/manual/en/pdo.error-handling.php ,默认情况下是静默的。

然后,是的,当查询失败时,PDO 应该发出一个异常,该异常将停止 try 部分的执行。在catch期间,您应该发出rollBack(),如果一切成功,您应该发出commit()。所以你的做法对我来说看起来是正确的。

启动事务后,在运行 commit() 之前,该连接中的任何内容都不会保存。 rollBack() 结束事务并返回到自动提交模式而不保存任何更改。

来自http://php.net/manual/en/pdo.begintransaction.php :

Turns off autocommit mode. While autocommit mode is turned off, changes made to the database via the PDO object instance are not committed until you end the transaction by calling PDO::commit(). Calling PDO::rollBack() will roll back all changes to the database and return the connection to autocommit mode.

关于php - 查询时临时锁定MYSQL表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27082692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com