Connection to postgres database failed

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SYT
    New Member
    • Mar 2008
    • 3

    Connection to postgres database failed

    Hello,

    I got "Connection to database failed." error from the following C program. Could anyone help me to solve this problem?

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

    int
    main()
    {
    char state_code[3];
    char query_string[256];
    PGconn *conn;
    PGresult *res;
    int i;

    conn = PQconnectdb("ho st=127.0.0.1 dbname=ontology user=postgres password=postgr es port=5432");

    if (PQstatus(conn) == CONNECTION_BAD)
    {
    printf("Content-type: text/html%c%c",10,10 );fflush(stdout );
    printf("<html>" );
    printf("<body background=\"%s/background.gif\ ">", webPath);
    fprintf(stderr, "Connection to database failed.\n");
    fprintf(stderr, "%s", PQerrorMessage( conn));
    exit(1);
    printf("</body></html>");
    }


    sprintf(query_s tring,
    "SELECT * FROM term");

    res = PQexec(conn, query_string);

    if (PQresultStatus (res) != PGRES_TUPLES_OK )
    {
    printf("Content-type: text/html%c%c",10,10 );fflush(stdout );
    printf("<html>" );
    printf("<body background=\"%s/background.gif\ ">", webPath);
    fprintf(stderr, "SELECT query failed.\n");
    PQclear(res);
    PQfinish(conn);
    exit(1);
    printf("</body></html>");
    }

    for (i = 0; i < PQntuples(res); i++)
    printf("%s\n", PQgetvalue(res, i, 0));
    printf("Content-type: text/html%c%c",10,10 );fflush(stdout );
    printf("<html>" );
    printf("<body background=\"%s/background.gif\ ">", webPath);
    printf("<br><br ><font>Term Name: </font><font color=#FF0000>% s</font>",res);
    printf("</body></html>");

    PQclear(res);

    PQfinish(conn);

    return 0;
    }

    Thanks in advance.

    Regards,
    SYT
  • rski
    Recognized Expert Contributor
    • Dec 2006
    • 700

    #2
    Are you sure that PQconnectdb arguments are correct (dbname, username etc.)
    Is postgres running and listening for network connections on port 5432? Can you connect to postgres using psql client and PQconnectdb arguments
    Code:
    psql -h 127.0.0.1 -p 5432 -U username dbname
    ?

    Comment

    • SYT
      New Member
      • Mar 2008
      • 3

      #3
      Yes, I'm able to connect to postgres using the following command.

      1. psql -h 127.0.0.1 -p 5432 -U username dbname

      So, what should I do? Thanks.

      Comment

      Working...