You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
2.1 KiB
54 lines
2.1 KiB
11 months ago
|
Transactions
|
||
|
============
|
||
|
A transaction is a sequence of statements that are treated as one unit; either all of them occur or none of them.
|
||
|
|
||
|
Syntax and features vary somewhat based on the DBMS.
|
||
|
|
||
|
Classic example: moving money from one bank account to another.
|
||
|
|
||
|
Autocommit mode:
|
||
|
Every statement is treated as a transaction of its own.
|
||
|
Most DBMSs have autocommit mode on by default.
|
||
|
|
||
|
To do a multi-statement transaction: BEGIN...COMMIT
|
||
|
|
||
|
Systems support various means to explicitly ROLLBACK a transaction using if statements, etc.
|
||
|
|
||
|
SQLite Example:
|
||
|
---------------
|
||
|
CREATE TABLE Customers(
|
||
|
CustomerID INTEGER PRIMARY KEY,
|
||
|
Name TEXT NOT NULL
|
||
|
);
|
||
|
|
||
|
CREATE TABLE Accounts(
|
||
|
AccountID INTEGER PRIMARY KEY,
|
||
|
CustomerID INTEGER NOT NULL,
|
||
|
Balance INTEGER NOT NULL,
|
||
|
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID),
|
||
|
CHECK (Balance >= 0) /* Enforces a constraint that no account may be overdrawn. */
|
||
|
);
|
||
|
|
||
|
INSERT INTO Customers (Name) VALUES("DrKow");
|
||
|
INSERT INTO Accounts (CustomerID, Balance) VALUES(1,1000);
|
||
|
INSERT INTO Accounts (CustomerID, Balance) VALUES(1,2000);
|
||
|
|
||
|
/* This statement is a single-line transaction; since it failed for one row, it will not modify any rows. */
|
||
|
UPDATE Accounts SET Balance = Balance - 1500;
|
||
|
|
||
|
BEGIN;
|
||
|
UPDATE OR ROLLBACK Accounts SET Balance = Balance + 50 WHERE AccountID=1;
|
||
|
UPDATE OR ROLLBACK Accounts SET Balance = Balance / 0 WHERE AccountID=1; /* This makes it crash, but the transaction is safely rolled back. */
|
||
|
UPDATE OR ROLLBACK Accounts SET Balance = Balance - 50 WHERE AccountID=2;
|
||
|
COMMIT;
|
||
|
|
||
|
/* The following command will also be rolled back, because the non-negative balance constraint would be violated. */
|
||
|
BEGIN;
|
||
|
UPDATE OR ROLLBACK Accounts SET Balance = Balance + 5000 WHERE AccountID=1;
|
||
|
UPDATE OR ROLLBACK Accounts SET Balance = Balance - 5000 WHERE AccountID=2;
|
||
|
COMMIT;
|
||
|
|
||
|
/* Note that the "OR ROLLBACK" part is required in SQLite; if you run the command above without it, 5000 will be added to one account without deducting it from the other. */
|
||
|
|
||
|
SELECT Name,AccountID,Balance FROM Customers JOIN Accounts ON Customers.CustomerID=Accounts.CustomerID;
|