• 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') 也成功插入
  • 相关阅读:
    使用清华源进行pip install
    BERT和ULMFIT embedding比较文本分类结果
    Ubuntu16.04更新python3.5到python3.7
    base64方式显示控件
    在使用redis做缓存后,mybatis的延迟加载失效
    springboot:redis反序列化发生类型转换错误
    eclipse :代码自动补全不生效解决办法
    微信扫码支付:问题集锦
    微信扫码支付(4):统一下单
    微信扫码支付(3):获取验签秘钥
  • 原文地址:https://www.cnblogs.com/lottu/p/14109193.html
Copyright © 2020-2023  润新知