I'm trying to figure out how to do transactions in SQLite, but I've hit a wall. Let's say I want to transfer $50 from one person's account to another. Take a look at the following code. It's heavily commented.
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). 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 should my next steps be?
-- What statements should I use here?
Aucun commentaire:
Enregistrer un commentaire