2

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?

Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
venus.w
  • 2,171
  • 7
  • 28
  • 42

2 Answers2

2

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.

Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
1

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

Community
  • 1
  • 1