By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,254 Members | 2,418 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,254 IT Pros & Developers. It's quick & easy.

Connection to postgres database failed

P: 3
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("host=127.0.0.1 dbname=ontology user=postgres password=postgres 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_string,
"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
Mar 11 '08 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 700
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
Expand|Select|Wrap|Line Numbers
  1. psql -h 127.0.0.1 -p 5432 -U username dbname
  2.  
?
Mar 11 '08 #2

P: 3
SYT
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.
Mar 11 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.