我在 CentOS 7.3 上安装了 C++、Postgres 和 postgresql-devel。我也安装了 libpqxx-4.0。
然后我创建了这个 add_employee.cxx 文件并基于“简要示例”here .
#include <iostream>
#include <pqxx/pqxx>
int main(int, char *argv[])
{
pqxx::connection c("dbname=foobar user=jdoe password=smartpassword");
pqxx::work txn(c);
pqxx::result r = txn.exec(
"SELECT id "
"FROM Employee "
"WHERE name =" + txn.quote(argv[1]));
if (r.size() != 1)
{
std::cerr
<< "Expected 1 employee with name " << argv[1] << ", "
<< "but found " << r.size() << std::endl;
return 1;
}
int employee_id = r[0][0].as<int>();
std::cout << "Updating employee #" << employee_id << std::endl;
txn.exec(
"UPDATE EMPLOYEE "
"SET salary = salary + 1 "
"WHERE id = " + txn.quote(employee_id));
txn.commit();
}
我是这样编译的:
c++ add_employee.cxx -lpqxx -lpq
我运行 ./a.out 并看到了这个:
terminate called after throwing an instance of 'pqxx::broken_connection' what(): FATAL: Peer authentication failed for user "foobar"
Aborted
我通常需要数据库角色“jdoe”的密码才能登录。我该怎么做才能避免该错误?我想让 C++ 程序自动登录。我没有进入数据库的无密码身份验证。有没有办法让这个 C++ 程序在需要密码的情况下登录到 Postgres 数据库?
最佳答案
我怀疑这与您的 C++ 代码关系不大,更多的是与服务器设置有关。
我记得,API 访问总是通过网络进行的,因此请确保您的 pg_hba.conf
文件是正确的。
我发现一种对测试有用的方法:从同一本地网络上的另一台机器访问。
关于c++ - 当我的数据库身份验证需要密码时,如何让 pqxx(Postgres 的 C++ API)工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42639533/