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') 也成功插入


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM