Trying postgresql c++ interface : pqxx

Postgresql database have an official interface to C programming language and a C++ interface derived from that. C++ is a different language from C and i think it will be more easier to deal with.

Lets give a try on the newest linux mint 20.

1. install libpqxx-dev package (sudo apt-get installĀ  libpqxx-dev).

2. install codelite IDE (sudo apt-get installĀ  codelite).

3. install postgresql (sudo apt-get install postgresql).

4. create an user (user1) for connecting to postgresql.

5. create a database (hello).

6. Open up codelite and create workspace and project hello (g++ simple executable).

7. Righ click hello project and open settings to add pqxx include path to compiler, we can find the correct path from apt content libpqxx-dev. Add to include paths field if necessary, here on linux mint 20 we dont need to.

8. Add pqxx lib to linker setting on libraries search path and libraries fields, and again we can find the correct path from apt content libpqxx-dev and analyze where the libraries file exist (files with .so or .a extention).

9. Edit main.cpp and create a simple app to get current date time from postgres server.

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

int main(){

try{

std::cout<<“Postgresql pqxx test program.”<<std::endl;

pqxx::connection cn(“postgresql://user1:pass123@localhost/hello”);

if(cn.is_open()){
std::cout<<“Database opened : “<<cn.dbname()<<std::endl;
}else{
std::cout<<“Error : cant connect to database !”<<std::endl;
return 1;
}

auto sql = “select current_timestamp”;

pqxx::work w(cn);
pqxx::row r = w.exec1(sql);

std::cout<<“Server time is : “<<r[0].c_str()<<std::endl;

if(cn.is_open()) cn.disconnect();

}catch(const std::exception &e){
std::cerr << e.what() << std::endl;
return 1;
}

std::cout<<“Aplication end.”<<std::endl;
return 0;

}

10. Press Ctrl-F5 to do build and execute.

11. If terminal is not showing up then edit settings->preferences->terminal and pick the correct terminal program available.

12. Done.

Leave a Reply

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