简体   繁体   English

当数据库身份验证需要密码时,如何使pqxx(用于Postgres的C ++ API)正常工作?

[英]How do I get pqxx (the C++ API for Postgres) to work when my database authentication requires a password?

I installed C++, Postgres, and postgresql-devel on CentOS 7.3. 我在CentOS 7.3上安装了C ++,Postgres和postgresql-devel。 I installed libpqxx-4.0 too. 我也安装了libpqxx-4.0。

I then created this add_employee.cxx file and based it on the "brief example" here . 然后,我创建了这个add_employee.cxx文件,并基于此处的“简短示例”。

#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();
}

I compiled it with this: 我用这个编译它:

c++ add_employee.cxx -lpqxx -lpq

I ran ./a.out and saw this: 我跑了出去,看到了:

terminate called after throwing an instance of 'pqxx::broken_connection' what(): FATAL: Peer authentication failed for user "foobar" 引发'pqxx :: broken_connection'what()实例后终止调用:致命:用户“ foobar”的对等身份验证失败

Aborted 中止

I normally need a password for the database role "jdoe" to log in. What do I do to get around the error? 通常,数据库角色“ jdoe”需要密码才能登录。如何解决该错误? I want to have a C++ program log in automatically. 我想让一个C ++程序自动登录。 I do not have passwordless authentication into the database. 我没有无密码身份验证进入数据库。 Is there a way to have this C++ program log into the Postgres database despite requiring a password? 尽管需要密码,有没有办法让此C ++程序登录到Postgres数据库?

I suspect this has little to do with your C++ code, and more with you the server is set up. 我怀疑这与您的C ++代码无关,而更多与服务器设置有关。

As I recall, API access always goes over the network so make sure you pg_hba.conf file is correct. 我记得,API访问总是通过网络进行的,因此请确保pg_hba.conf文件正确。

One way I found useful for testing: access from another machine on the same local network. 我发现对测试有用的一种方法:从同一局域网中的另一台计算机进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM