PostgreSQL 如何忽略事务中错误

在 PostgreSQL 的事务中;执行的SQL遇到错误(书写,约束限制);该事务的已经执行的SQL都会进行rollback。那如何忽略其中的错误。将SQL执行到底?在事务中设置 ON_ERROR_ROLLBACK 即可。

下面演示

1、未作任何设置

演示脚本

begin;
-- 1、创建表tbl_test_01
create table tbl_test_01(id int primary key, info text);
-- 2、插入异常数据
insert into tbl_test_01 values ('hello', 'PostgreSQL');
-- 3、插入正常数据
insert into tbl_test_01 values (1001, 'PostgreSQL');
end;

执行过程

postgres=# begin;
BEGIN
postgres=# create table tbl_test_01(id int primary key, info text);
CREATE TABLE
postgres=# insert into tbl_test_01 values ('hello', 'PostgreSQL');
ERROR:  invalid input syntax for type integer: "hello"
LINE 1: insert into tbl_test_01 values ('hello', 'PostgreSQL');
                                        ^
postgres=# insert into tbl_test_01 values (1001, 'PostgreSQL');
ERROR:  current transaction is aborted, commands ignored until end of transaction block
postgres=# end;
ROLLBACK
postgres=# \d tbl_test_01
Did not find any relation named "tbl_test_01".

执行结果

  • 执行结果是ROLLBACK
  • 执行的正常SQL也ROLLBACK

2、设置 ON_ERROR_ROLLBACK

演示脚本

begin;
\set ON_ERROR_ROLLBACK interactive
create table tbl_test_01(id int primary key, info text);
insert into tbl_test_01 values ('hello', 'PostgreSQL');
insert into tbl_test_01 values (1001, 'PostgreSQL');
end;

执行过程

postgres=# begin;
BEGIN
postgres=# \set ON_ERROR_ROLLBACK interactive
postgres=# create table tbl_test_01(id int primary key, info text);
CREATE TABLE
postgres=# insert into tbl_test_01 values ('hello', 'PostgreSQL');
ERROR:  invalid input syntax for type integer: "hello"
LINE 1: insert into tbl_test_01 values ('hello', 'PostgreSQL');
                                        ^
postgres=# insert into tbl_test_01 values (1001, 'PostgreSQL');
INSERT 0 1
postgres=# end;
COMMIT
postgres=# \d tbl_test_01
            Table "public.tbl_test_01"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 id     | integer |           | not null | 
 info   | text    |           |          | 
Indexes:
    "tbl_test_01_pkey" PRIMARY KEY, btree (id)
postgres=# select * from tbl_test_01;
  id  |    info    
------+------------
 1001 | PostgreSQL
(1 row)

执行结果

  • 执行结果是COMMIT
  • 表 tbl_test_01 成功创建
  • 数据 (1001, 'PostgreSQL') 也成功插入
posted @ 2020-12-09 16:03  lottu  阅读(1564)  评论(0编辑  收藏  举报