#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    2
    Rep Power
    0

    [SOLVED] Libpq - Connection to database failed: timeout exired


    I have PostgreSQL 9.3 (x86) installed, the server service is up (status = Started) and I can connect to it with pgAdmin.

    On the server there is a database: postgres and it's owner is user "postgres" with password "admin". The server is running on localhost, port 5433.

    Yet when I try to access my database from C++ code with the following code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <libpq-fe.h>
    
    static void exit_nicely(PGconn *conn)
    {
        PQfinish(conn);
        exit(1);
    }
    
    int main(int argc, char **argv)
    {
        const char *conninfo;
        PGconn     *conn;
    
        conninfo = "host=localhost port=5433 dbname=postgres user=postgres password=admin connect_timeout=5";
    
    	fprintf(stdout, "# Start\n");
    
        conn = PQconnectdb(conninfo);
        if (PQstatus(conn) != CONNECTION_OK)
        {
            fprintf(stderr, "Connection to database failed: %s",
                    PQerrorMessage(conn));
            exit_nicely(conn);
        }
    
    	fprintf(stdout, "# Connected\n");
    
        PQfinish(conn);
    
        return 0;
    }
    I get an error: "Connection to database failed: timeout exired"

    I'd be grateful for any clues what might cause such a behavior
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    158
    Rep Power
    11
    is your server listening on "localhost"? Can your application resolve that to the correct IP?

    I trust that you are able you connect through the psql commandline?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    2
    Rep Power
    0
    Originally Posted by Vinny42
    is your server listening on "localhost"? Can your application resolve that to the correct IP?

    I trust that you are able you connect through the psql commandline?
    Hey Vinny, thank you for your response!
    I did some testing with psql and found out that the time needed to connect to the db on my system is ~30-40 sec. So all I had to do was to set connect_timeout parameter to let's say 60 and the problem is gone
    Such a stupid thing..
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    158
    Rep Power
    11
    the time needed to connect to the db on my system is ~30-40 sec
    40 seconds to connect? Don't you mean 40 milliseconds?

IMN logo majestic logo threadwatch logo seochat tools logo