如何在 psql 中获取 Postgresql 错误号?

Mar*_*son 4 postgresql psql errors

如何访问 中错误的数字代码psql

例如,在本例中,我想获取值 23503(“foreign_key_violation”),如下所示: https: //www.postgresql.org/docs/current/errcodes-appendix.html

postgres=# insert into t values('bb');
ERROR:  insert or update on table "t" violates foreign key constraint "fd"

-- How can I see the numeric error code here?
Run Code Online (Sandbox Code Playgroud)

mus*_*cio 6

您可以将VERBOSITY特殊变量设置为sqlstate,这将导致在当前会话中任何失败的语句之后打印 SQLSTATE 代码:

\set VERBOSITY sqlstate
Run Code Online (Sandbox Code Playgroud)

或者,您可以按需打印 SQLSTATE 代码:

\echo :LAST_ERROR_SQLSTATE
Run Code Online (Sandbox Code Playgroud)


Lau*_*lbe 5

Mustaccio 的答案很好,但是如果您需要的只是查看刚刚出现的错误的 SQLSTATE psql,那么最简单的方法是运行

\errverbose
Run Code Online (Sandbox Code Playgroud)

请注意,SQLSTATE 并不总是数字。