I program with libpq.so. I want to get the error code which is called sql state in SQL Standard.How should I get this in my c code?
2 Answers
The obvious Google search for libpq get sqlstate
finds the libpq-exec documentation. Searching that for SQLSTATE
finds PG_DIAG_SQLSTATE
in the PQresultErrorField
section.
Thus, you can see that you can call PQresultErrorField(thePgResult, PG_DIAG_SQLSTATE)
to get the SQLSTATE
.

- 307,061
- 76
- 688
- 778
This is just addition I can not leave in form of comment due to reputation reasons.
Note that you can not portably get SQLSTATE for errors that can occur during PQconnectdb
. In theory, you can read pg_conn
(internal struct) field last_sqlstate
which contains correct value.
For example, if you try to connect with invalid login/password, it will give you 28P01
. For wrong database it will contain 3D000
.
I wish they defined publically available getter for this field.
You can check this one as well: libpq: How to get the error code after a failed PGconn connection

- 1
- 1

- 265
- 3
- 11
-
Please consider submitting a patch for this. – Craig Ringer Apr 11 '17 at 03:05