結構化查詢語言/COMMIT 和 ROLLBACK
DBMS 提供了一種特殊的服務。我們可以撤銷單個或多個連續的寫入和刪除操作。為此,我們使用 ROLLBACK 命令。在修改資料時,DBMS 首先將所有新資料、更改資料或刪除資料寫入臨時空間。在此階段,修改後的資料不屬於“常規”資料庫的一部分。如果我們確定修改應該應用,我們使用 COMMIT 命令。如果我們想要恢復更改,我們使用 ROLLBACK 命令。所有最終提交或回滾之前的更改都屬於所謂的事務。
COMMIT 和 ROLLBACK 的語法非常簡單。
COMMIT WORK; -- commits all previous INSERT, UPDATE and DELETE commands, which
-- occurred since last COMMIT or ROLLBACK
ROLLBACK WORK; -- reverts all previous INSERT, UPDATE and DELETE commands, which
-- occurred since last COMMIT or ROLLBACK
關鍵字“WORK”是可選的。
AUTOCOMMIT 功能在每次寫入操作(INSERT、UPDATE 或 DELETE)後自動執行 COMMIT。此功能不是 SQL 標準的一部分,但在某些實現中已實現並預設啟用。如果我們想使用 ROLLBACK 命令,我們必須停用 AUTOCOMMIT。(在自動或顯式 COMMIT 命令之後,ROLLBACK 命令在語法上是正確的,但它不會執行任何操作,因為一切都已提交。)通常,我們可以使用單獨的命令(如“SET autocommit = 0;”或“SET autocommit off;”)或透過點選 GUI 上的圖示來停用 AUTOCOMMIT。
要測試以下語句,必須在無 AUTOCOMMIT 的情況下工作。
讓我們將一個新人插入到資料庫中並測試 COMMIT。
-- Store a new person with id 99.
INSERT INTO person (id, firstname, lastname, date_of_birth, place_of_birth, ssn, weight)
VALUES (99, 'Harriet', 'Flint', DATE'1970-10-19', 'Dallas', '078-05-1120', 65);
-- Is the new person really in the database? The process which executes the write operation will see its results,
-- even if they are actually not committed. (One hit expected.)
SELECT *
FROM person
WHERE id = 99;
-- Try COMMIT command
COMMIT;
-- Is she still in the database? (One hit expected.)
SELECT *
FROM person
WHERE id = 99;
現在我們從資料庫中刪除該人。
-- Remove the new person
DELETE
FROM person
WHERE id = 99;
-- Is the person really gone? Again, the process which performs the write operation will see the changes, even
-- if they are actually not committed. (No hit expected.)
SELECT *
FROM person
WHERE id = 99;
-- Try COMMIT command
COMMIT;
-- Is the person still in the database? (No hit expected.)
SELECT *
FROM person
WHERE id = 99;
到目前為止,一切都那麼無聊。
令人興奮的命令是 ROLLBACK。它會恢復之前 INSERT、UPDATE 或 DELETE 命令的更改。
我們將從示例資料庫中刪除漢密爾頓夫人並恢復她。
DELETE
FROM person
WHERE id = 3; -- Lisa Hamilton
-- no hit expected
SELECT *
FROM person
WHERE id = 3;
-- ROLLBACK restores the deletion
ROLLBACK;
-- ONE hit expected !!! Else: check AUTOCOMMIT
SELECT *
FROM person
WHERE id = 3;
ROLLBACK 不限於單行。它可能影響多行、多個命令、不同型別的命令,甚至多個表。
-- same as above
DELETE
FROM person
WHERE id = 3;
-- destroy all e-mail addresses
UPDATE contact
SET contact_value = 'unknown'
WHERE contact_type = 'email';
-- verify modifications
SELECT * FROM person;
SELECT * FROM contact;
-- A single ROLLBACK command restores the deletion in one table and the modifications in another table
ROLLBACK;
-- verify ROLLBACK
SELECT * FROM person;
SELECT * FROM contact;
假設愛好表包含 9 行,人員表包含 10 行。我們執行以下操作
新增 3 個愛好
新增 4 個人
提交
新增 5 個愛好
新增 6 個人
回滾
愛好表中有多少行?
12
人員表中有多少行?
14