事务操作

最近更新时间: 2026-03-13 09:03:00

事务操作包括BEGIN(开启事务),COMMIT(提交事务),ROLLBACK(回滚事务)还有SAVEPOINT(保存点),用于控制和管理事务行为。

开启事务

BEGIN开始一个事务块,BEGIN命令之后的所有语句将被在一个事务中执行,直到给出一个显式的COMMIT或ROLLBACK。

语法

BEGIN [ WORK | TRANSACTION ] [ transaction_mode [, ...] ]
  • transaction_mode 可以是:
    ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED | READ UNCOMMITTED }
    READ WRITE | READ ONLY
    [ NOT ] DEFERRABLE

    说明:

    如果不指定transaction_mode,会使用默认隔离级别,READ COMMITTED(读已提交)。

提交事务

COMMIT提交当前事务,所有由该事务所作的更改将持久保存在数据库中。

语法

COMMIT [ WORK | TRANSACTION ]

示例

drop table t1;
create table t1(id int);

begin;
insert into t1 values(1);
select * from t1;
 ID
----
  1
(1 row)
commit;

-- after the commit is executed, the data is truly inserted into the database.
select * from t1;
 ID
----
  1
(1 row)

回滚事务

ROLLBACK中止一个事务,该事务的所有操作将撤销。

语法

ROLLBACK [ WORK | TRANSACTION ]

示例

drop table t1;
create table t1(id int);

begin;
insert into t1 values(1);
select * from t1;
 ID
----
  1
(1 row)
rollback;

-- after a rollback is performed, the data is not actually inserted into the database.
select * from t1;
 ID
----
(0 rows)

AUTOCOMMIT模式

注意,以上均为显示开启事务块的场景。如果不显示开启事务块,则默认采用autocommit模式,即自动提交。

示例

drop table t1;
create table t1(id int);

insert into t1 values(1);
select * from t1;
 ID
----
  1
(1 row)