简体   繁体   中英

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. I installed libpqxx-4.0 too.

I then created this add_employee.cxx file and based it on the "brief example" 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();
}

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"

Aborted

I normally need a password for the database role "jdoe" to log in. What do I do to get around the error? I want to have a C++ program log in automatically. 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?

I suspect this has little to do with your C++ code, and more with you the server is set up.

As I recall, API access always goes over the network so make sure you pg_hba.conf file is correct.

One way I found useful for testing: access from another machine on the same local network.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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