7

我只是在阅读 RDBMS,RDBMS 的一个属性是原子性。因此,如果从一个帐户中提取资金并转移到另一个帐户,则交易要么完全发生,要么根本不发生。没有部分交易。但实际上如何保证?

上述场景的 Sql 查询可能看起来像 (i) UPDATE accountsset balance = balance - amount WHERE ac_num = 101 (ii) UPDATE accountsset balance = balance + amount WHERE ac_num = 102

这决不能确保原子性。那么它实际上是如何发生的呢?

4

2 回答 2

8

如果你这样做

BEGIN TRANSACTION
UPDATE accounts set balance = balance - amount WHERE ac_num = 101
UPDATE accounts set balance = balance + amount WHERE ac_num = 102
COMMIT TRANSACTION

数据库系统将对帐户 101 所做的更改写入注释。然后,如果帐户 102 上的工作失败,RDBMS 将使用这些注释撤消对 101 的工作。

此外,当它在帐户 101 上开始工作时,它会锁定数据库,这样其他人就无法读取帐户 101 中更新但未提交的数据。(这里的锁定基本上只是某处的注释“我在这里工作,请勿触摸。”)

于 2009-03-28T10:25:58.440 回答
4

要成为原子事务,事务需要:

  • 防止其他事务干扰它们正在写入或读取的行
  • 确保在事务提交时,事务所做的所有更改或没有更改将在数据库中。

第一个是通过锁定事务在执行期间读取或写入的行来实现的。

Second one is done so that transactions write their actions into a transaction log. This makes the database able to recover even when the server loses power during a transaction. In this case the recovery process will read the log, make sure that active (uncommited) transactions get aborted and changes made by them are canceled.

于 2009-03-28T11:58:09.717 回答