PostgreSQL11: psql 新增变量记录SQL语句的执行情况和错误

栏目: 数据库 · PostgreSQL · 发布时间: 7年前

内容简介:PostgreSQL 11 版本新增加 ERROR、SQLSTATE、ROW_COUNT、LAST_ERROR_MESSAGE、LAST_ERROR_SQLSTATE 五个变量用来记录SQL语句的执行结果状态和错误信息。这些变量的值随着SQL执行后进行刷新,主要用来编写脚本时捕获SQL的执行结果。关于这几个变量的说明如下:

PostgreSQL 11 版本新增加 ERROR、SQLSTATE、ROW_COUNT、LAST_ERROR_MESSAGE、LAST_ERROR_SQLSTATE 五个变量用来记录 SQL 语句的执行结果状态和错误信息。

这些变量的值随着SQL执行后进行刷新,主要用来编写脚本时捕获SQL的执行结果。

Release 说明

Add psql variables to report query activity and errors (Fabien Coelho) Specifically, the new variables are ERROR, SQLSTATE, ROW_COUNT, LAST_ERROR_MESSAGE, and LAST_ERROR_SQLSTATE.

变量解释

关于这几个变量的说明如下:

**ERROR**
true if the last SQL query failed, false if it succeeded. See also SQLSTATE.

**SQLSTATE**
The error code (see Appendix A) associated with the last SQL query is failure, or 00000 if it succeeded.

**ROW_COUNT**
The number of rows returned or affected by the last SQL query, or 0 if the query failed or did not report a row count.

**LAST_ERROR_MESSAGE**
**LAST_ERROR_SQLSTATE**
The primary error message and associated SQLSTATE code for the most recent failed query in the current psql session, or an empty string and 00000 if no error has occurred in the current session.

这几个变更的解释很容易理解,下面演示下。

演示:SQL执行成功

正常执行一条SQL,执行后查看 ERROR、SQLSTATE、ROW_COUNT 变量,如下:

[pg11@pghost2 ~]$ psql francs francs
psql (11beta3)
Type "help" for help.

francs=> SELECT * FROM generate_series(1,3);
 generate_series
-----------------
               1
               2
               3
(3 rows)

francs=> \echo :ERROR
false

francs=> \echo :SQLSTATE
00000

francs=> \echo :ROW_COUNT
3

演示:SQL执行失败

SQL执行失败,执行后查看 ERROR、SQLSTATE、ROW_COUNT 变更,如下:

francs=> SELECT *,afcd FROM generate_series(1,3);
ERROR:  column "afcd" does not exist
LINE 1: SELECT *,afcd FROM generate_series(1,3);
                 ^
francs=> \echo :ERROR
true

francs=> \echo :SQLSTATE
42703

francs=> \echo :ROW_COUNT
0

francs=> \echo :LAST_ERROR_MESSAGE
column "afcd" does not exist

francs=> \echo :LAST_ERROR_SQLSTATE
42703

SQLSTATE 变量返回SQL报错代码,SQL报错代码可参考手册 PostgreSQL Error Codes

参考


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms Illuminated (Part 2)

Algorithms Illuminated (Part 2)

Tim Roughgarden / Soundlikeyourself Publishing, LLC / 2018-8-5 / USD 17.99

Algorithms are the heart and soul of computer science. Their applications range from network routing and computational genomics to public-key cryptography and machine learning. Studying algorithms can......一起来看看 《Algorithms Illuminated (Part 2)》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具