我想知道如何在插入等之后获取postgres sql错误代码。?
答案 0 :(得分:0)
以下是文档中的代码段:
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;
}
一旦遇到sql_error,您可以从中检索sql状态:
std::cerr << "SQL STATE: " << s->sqlstate() << std::endl;
因此更改上面的代码段:
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;
}
}
鉴于表名是company,而不是compamy,将获得以下输出:
SQL Error code: 42P01
从Postgresql error codes表中查找该代码:
42P01 undefined_table