Tomtom
Tomtom

Reputation: 55

How can I get the postgres sqlerrorcode with libpqxx?

I would like get to know how to get the postgres sql error code after an insert etc.. ?

Upvotes: 0

Views: 971

Answers (2)

fgwe84
fgwe84

Reputation: 168

For a newer version of libpqxx catch pqxx::sql_error

try {
    //
}
catch ( const pqxx::sql_error &e ) {
    std::cerr << e.what() << std::endl;
    std::cerr << "Query was: " << e.query() << std::endl;
}

Upvotes: 0

Tom D
Tom D

Reputation: 29

Here is a code snippet right from the documentation:

try
{
  // ...
}
catch (const pqxx::pqxx_exception &e)
{
  std::cerr << e.base().what() << std::endl;
  const pqxx::sql_error *s=dynamic_cast<const pqxx::sql_error*>(&e.base());
  if (s) std::cerr << "Query was: " << s->query() << std::endl;
}

Once you have the sql_error you can retrieve the sql state from that:

std::cerr  << "SQL STATE: " << s->sqlstate() << std::endl;

So changing the above code sippet:

pqxx::connection dbConn("dbname=tester user=foo");
pqxx::result r;
try
{
  pqxx::work transx(dbConn);
  std::string query ("SELECT name FROM compamy");
  r = transx.exec(query);
  transx.commit();  // Not necessary for a SELECT, but good practice
}
catch (const pqxx::pqxx_exception &e)
{
  std::cerr << e.base().what() << std::endl;
  const pqxx::sql_error *s=dynamic_cast<const pqxx::sql_error*>(&e.base());
  if (s) {
    std::cerr << "SQL Error code: " << s->sqlstate() << std::endl;
  }
}

Given that the table name is company, not compamy, nets the following output:

SQL Error code: 42P01

Looking up that code from the Postgresql error codes table:

42P01   undefined_table

Upvotes: 1

Related Questions