Thursday, August 28, 2014

Codeblocks, PostgreSQL and C

I started working on the next steps for my parser. I want it to write the data straight into my db (which uses PostgreSQL). It's a simple enough plan, that should require just a few small adjustments from my parser... in theory. :)

I started with an obvious and misleading Google search for C++ and PostgreSQL... which lead me to the libpq++ library... which looked fine until I noticed that it is only documented for PostgreSQL version 7... which is not a good sign given that Im using version 9.3... that lead to another search which landed me to the currently official library libpq-fe.h, which is a C library but also the official way to interact with Postgres from C/C++

So I write a small program to simply read a table from the DB and print it out to terminal, based on this tutorial: http://www.postgresql.org/docs/8.3/static/libpq-example.html

I made a few modifications to it, so that it'll read from my table and use my db... and everything looked fine... except that I kept getting and "undeclared reference to PQ... " everytime I tried to compile it. 


This lead to a few hours of back and forths with google and stackexchange... during which I made sure I had installed the correct libraries, found that unlike other Linux distros, Fedora puts libpq-fe.h in the best folder /usr/include/ and that everything should work fine after I add the -lpq flag to the compiler. So, I go to codeblocks compiler settings other options and add -lpq as a flag... which doesn't work. :( After a few back and forths (and re-checking everything one last time) I go into the terminal and compile from there using: "g++ main.cpp -lpq" whcih works just fine... So I ask around and get a very educational lesson on Makefiles and on why IDE's suck from my coworkers. I learn that I should've been putting that -lpq flag on the Linker settings for codeblocks... so, after adding pq to Link libraries I am able to read from the DB (Yippy!!!) and print the table to terminal. Which means that Im one step closed to writting my parser directly into the db. 

1 comment:

  1. Very good efforts. You can find more on porting data from CSV files to postgress using cpp is well explained here. you may try this when you encounter the scenario.

    Reading data from CSV file and writing it into the PostgreSQl database in C++

    ReplyDelete