你究竟在SQLite中做什么交易?

时间:2016-02-04 08:22:06

标签: sql sqlite transactions

我试图弄清楚如何在SQLite中进行交易,但我已经碰壁了。让我们说我想将50美元从一个人的账户转移到另一个人账户。看看下面的代码。它评论很多。

DROP TABLE IF EXISTS accounts;
CREATE TABLE IF NOT EXISTS accounts (
    name       VARCHAR(20) NOT NULL,
    balance    INTEGER         NULL -- Money is going to be stored in cents
);

INSERT INTO accounts (name, balance) VALUES
("John Doe",  10050), -- This means 100 dollars and 50 cents
                      -- because 100 dollars and 50 cents is
                      -- 100 * 100 cents + 50 cents = 10050 cents
("Bob Smith", 20000); -- 200 dollars



DROP VIEW IF EXISTS view_accounts;
CREATE VIEW view_accounts AS
    SELECT rowid,
           name,
           printf("$%.2f", balance / 100.0) AS balance
    FROM accounts;

SELECT * FROM view_accounts;
-- rowid       name        balance
-- ----------  ----------  ----------
-- 1           John Doe    $100.50
-- 2           Bob Smith   $200.00



BEGIN TRANSACTION;

-- Subtract $50 from John Doe's balance
UPDATE accounts SET balance = balance - 5000 WHERE rowid = 1;
-- And add $50 to Bob Smith's balance, but let's now intentionally
-- create something erroneous here. Let's say there's been a mistake
-- and we got the wrong rowid (maybe we received an id that does not
-- exist in our table from a host language such as PHP, but really it
-- could be anything from power-down to inadvertent reboot. I'm using
-- this particular example because it's easy to emulate an exceptional
-- situation). Instead of rowid 2, we mistakenly used a rowid of 3
-- which does not exist in our table.
UPDATE accounts SET balance = balance + 5000 WHERE rowid = 3;

-- Here's where I get stuck. What exactly should my next steps be?
-- What statements should I use here? Obviously I should roll all the
-- changes made so far back with the ROLLBACK command if something
-- exceptional happens, but I can't know that beforehand because the
-- value for rowid is received from external sources. On the other hand,
-- I can't use COMMIT either because what if in fact something
-- exceptional did happen? I somehow need to detect that something bad
-- has happened and conditionally either roll all the changes back or, if
-- everything is okay, commit them.

1 个答案:

答案 0 :(得分:2)

由于SQLite没有任何流控制语句,因此无法单独在SQLite中执行此操作。

您正在寻找的内容类似于此伪代码:

IF rows-affected = 0 THEN ROLLBACK TRANSACTION

ROLLBACK TRANSACTION替换为您想要的任何类型的错误响应。

由于SQLite语法中没有IF语句或类似语句,因此如果没有使用SQLite的代码/编程语言/运行时的帮助,就无法做到这一点。

换句话说,最终调用SQLite的编程语言需要查看SQLite引擎报告的受影响的行数,并处理零。

请注意,您要回滚事务的事实是对错误的响应的一部分,但此问题与事务本身无关。基本上你的问题是关于流量控制。