c++ - 当我的数据库身份验证需要密码时,如何让 pqxx(Postgres 的 C++ API)工作?

标签 c++ postgresql libpqxx

我在 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/

相关文章:

c++ - 如何在 postgresql 的 c++ 中使用 pqxx 在 sql 查询中执行 IN?

c++ - 这是设计缺陷吗?

sql - 即使没有匹配查询的行,如何强制 postgres 返回 0,使用 coalesce,group by 和 join

c++ - 模板模板函数的重载

postgresql - 如何按计数结果归一化分组?

sql - Postgresql-将 10 秒条目的表压缩为 1 分钟条目的最佳方法

c++ - 如何在 Postgresql for C++ 中准备语句和绑定(bind)参数

postgresql - 从 libpqxx 创建 plpgsql 函数

c++ - Opencv3.1,SURf,报错

c++ - C++ 中具有 const 成员的类数组