📜  PostgreSQL – 回滚

📅  最后修改于: 2022-05-13 01:57:05.530000             🧑  作者: Mango

PostgreSQL – 回滚

PostgreSQL ROLLBACK命令用于撤消事务中所做的更改。正如我们所知,数据库语言中的事务用于大型计算,例如在银行中。假设银行员工错误地增加了错误人的余额记录,那么他可以简单地回滚并回到之前的状态。

句法:

ROLLBACK TRANSACTION;

(or)

ROLLBACK;

(or)

ROLLBACK WORK;

要了解 ROLLBACK 命令的重要性,首先让我们构建一个示例表。

CREATE TABLE BankStatements (
    customer_id serial PRIMARY KEY,
    full_name VARCHAR NOT NULL,
    balance INT
);

现在我们将插入一些客户的数据

INSERT INTO BankStatements (
    customer_id ,
    full_name,
    balance
)
VALUES
    (1, 'Sekhar rao', 1000),
    (2, 'Abishek Yadav', 500),
    (3, 'Srinivas Goud', 1000);

现在表格准备好了,我们将了解提交

示例 1:

我们将使用提交将数据添加到事务中的表中

BEGIN;

 INSERT INTO BankStatements (
     customer_id,
    full_name,
        balance
)
    VALUES (
       4, 'Priya chetri', 500
       
)
;

SELECT * FROM BankStatements;
        
ROLLBACK;

SELECT * FROM BankStatements;

输出:

示例 2:

BEGIN;


    UPDATE BankStatements
      SET balance = balance - 500
      WHERE 
      customer_id = 1;
      
      // displaying data before
      // commmiting the transaction
      SELECT customer_id, full_name, balance
      FROM BankStatements;
      
      UPDATE BankStatements
      SET balance = balance + 500
      WHERE 
      customer_id = 2;
 
       
ROLLBACK;

// displaying data after
// commmiting the transaction
SELECT customer_id, full_name, balance
FROM BankStatements;

输出: