Question

I'm a complete novice trying to learn PostgreSQL. I'm trying to connect to my postgres server throught a C program using libpq.

Here is the server status:

home/planb/postgresql-9.2.4/Project status -o "-p 5555"
pg_ctl: server is running (PID: 2338)
/usr/local/pgsql/bin/postgres "-D" "/home/planb/postgresql-9.2.4/Project" "-p5555"

When I compile, I use:

gcc -I /usr/local/pgsql/include -L /usr/local/pgsql/lib test.c -lpq

When I run the program with ./a.out, it reads:

Connection error

I believe I'm not using PQconnectdb correctly, but it could be other things.

Here is my C file: test.c

#include <stdio.h>
#include <stdlib.h>  
#include <libpq-fe.h>

int main(int argc, char* argv[])
{
//Start connection
PGconn* connection = PQconnectdb("hostaddr=168.105.127.3 port=5555 dbname=Project username=postgres password=password");

if (PQstatus(connection) ==CONNECTION_BAD)
    {
    printf("Connection error\n");
    PQfinish(connection);
    return -1; //Execution of the program will stop here
    }
    printf("Connection ok\n");
    //End connection
    PQfinish(connection);
    printf("Disconnected\n");
    return 0;
}

Any input is greatly appreciated, thanks!

Figured it out!

I wasn't using a valid hostaddr. I replaced it with:

host=localhost

I also deleted dbname=Project. When I run it, I get:

Msg: Connection ok
Disconnected
Was it helpful?

Solution

Here is the solution to my problem:

I wasn't using a valid hostaddr. The correct way for me to connect to my own local server was with:

host=localhost

I also deleted dbname=Project. I was getting a message saying that it wasn't a real database. I guess I didn't need to call dbname in PQconnectdb.

Now when I run it with these changes, I get:

Msg: Connection ok
Disconnected

OTHER TIPS

Try this out

#include <libpq-fe.h>
#include <stdio.h>
#include <string>
#include <iostream>
void main(){
string m_strHost="127.0.0.1";
string m_strPort="5433";
string m_strUser="postgres";
string m_strPassword="postgres";
string m_strDataBase="postgres";

string strConnection="hostaddr="+m_strHost+" "+"port="+m_strPort+" "+"user="+m_strUser+" "+"password="+m_strPassword+" "+"dbname="+m_strDataBase;
cout <<"\n ctrstring =  "<<strConnection;

char *pcon = const_cast<char*>(strConnection.c_str());
conn = PQconnectdb(pcon);
cout <<"\n";
//conn = PQconnectdb("user=postgres password=postgres dbname=postgres hostaddr=127.0.0.1 port=5433");

// Check to see that the backend connection was successfully made
if (PQstatus(conn) != CONNECTION_OK)
{
    cout<<"Connection to database failed";
    PQfinish(conn);
}else { cout<<"Connection to database - OK\n";}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top