PDO 交易?
如果使用 PDO 事务,是否需要锁定表?
如果用户a有50个钱,并向用户b转账50个,PDO交易是否能确保它们都正确执行?
另外,如果说我有一个 if 语句,例如,
if ($user['money'] > 500) {
$dbc ->beginTransaction();
.........
$dbc ->commit();
}
如何确保用户资金的价值不会改变,这意味着在事务运行时不应运行查询? 谢谢
Do I need to lock tables if I use PDO transactions?
If user a has 50 money and transfers 50 to user b, will PDO transaction make sure they all get executed without error?
Also if say I have a if statement like,
if ($user['money'] > 500) {
$dbc ->beginTransaction();
.........
$dbc ->commit();
}
How can I ensure that the value of the users' money doesn't change meaning the query shouldn't run, while the transaction is running??
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事务处理由SQL Server保证。如果 beginTransaction() 成功,commit() 成功并且您的 SQL 服务器和表支持事务,那么您就可以确定这一点。
Transaction process is guaranteed by SQL server. If beginTransaction() succeeds, commit() succeeds and your SQL server and table supports transactions, then you can be sure about it.
PDO是一个抽象层,所以它取决于你的数据库。 MySQL 支持事务,但仅适用于 InnoDB 表。否则只能使用表锁(这是不一样的)。 SQLite 始终支持事务。另一个数据库可能永远不会。
交易仍然需要您(开发人员)创建和验证逻辑。数据库不知道什么是正确的(正确,而不只是)和什么是错误的(不正确)。确实如此,因此您必须创建一个在适当时调用 BEGIN 和 COMMIT/ROLLBACK 的脚本。
另外值得注意的是:事务在数据库错误后不会自动回滚。 (也许某些数据库或 DBAL 会这样做,但它不是标准的,您不应该依赖它。)这意味着您必须检查每个查询的结果/响应/反馈并采取适当的行动(例如,通过调用 ROLLBACK)。
PDO is an abstraction layer, so it depends on your database. MySQL supports transactions, but only for InnoDB tables. Otherwise only with table locks (which is not the same). SQLite always supports transactions. Another database might never.
Transactions still require YOU (the developer) to create and verify the logic. The database doesn't know what's right (correct, not just) and what's wrong (incorrect). You do, so you have to create a script that calls BEGIN and COMMIT/ROLLBACK when appropriate.
Also worth noting: a transaction isn't automatically ROLLBACKed after a database error. (Maybe some databases or DBALs do, but it's not standard and you shouldn't count on it.) Which means YOU have to check the result/response/feedback of every query AND act appropriately (eg. by calling a ROLLBACK).