结构化查询语言/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