How Do You Use the C++ Connector for Libpqxx?

Problem scenario
You want to integrate C++ programs with Postgresql on an Ubuntu instance of AWS.  You want to use pqxx (http://pqxx.org/development/libpqxx/) as it is an API connector for C++ to Postgres.  How do you use libqxx?

Solution
#1  Install Postgresql.  To install Postgresql, run this as root or with a "sudo " in front of it: apt-get install postgresql

#2  To execute SQL commands, use this the following Linux commands:

sudo -i -u postgres

psql

#3  Create a ROLE with a user that can log in.  For example, run this (but substitute contuser with the username and integ3727 with the password of your choice):

CREATE ROLE contuser WITH LOGIN PASSWORD 'integ3727';

#4  Exit the Postgres database by running these two commands:

\q

exit

#5  Install libpqxx.  See this link if necessary.

#6  Create a test program (e.g., contint.cpp).  The content of this program (e.g., contint.cpp) should be the following (and please note that every line except the "connection" line was taken from this link).

#include <iostream>
#include <pqxx/pqxx>

using namespace std;
using namespace pqxx;

int main(int argc, char* argv[])
{
   try{
      connection C("dbname=postgres user=contuser password=integ3727 \
      hostaddr=127.0.0.1 port=5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }
      C.disconnect ();
   }catch (const std::exception &e){
      cerr << e.what() << std::endl;
      return 1;
   }
}

#7  Compile the program using a special command (substitute contint.cpp with the name of your C++ program):
# g++ -I /usr/local/include/pqxx/ -L /usr/local/lib/ -I /usr/local/pgsql/include/ -L /usr/local/pgsql/lib/ contint.cpp -lpqxx -lpq

Citation: This command was largely taken from this link.

#8  Run the byte code to prove it all works:

./a.out

Leave a comment

Your email address will not be published. Required fields are marked *