469,921 Members | 2,221 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,921 developers. It's quick & easy.

Query regarding odbc connection ??

Hi All

Problem : I am unable to retrieve the data from the table in postgres database using C application which i have written in solaris os.

Query: How to check whether connection is there between postgres database and C application(which we have written for accessing the database) ?

My code is comiling successfully if i run it then its giving o/p as following :


-bash-3.00$ ./odbc
Enter a max bw: 20
SELECT query failed.

C code:

#include <stdio.h>
#include <stdlib.h>
# include <libpq-fe.h>
int main()
int entered_bw; /* holds max_bw entered by user */

char query_string[256]; /* holds constructed SQL query */
PGconn *conn; /* holds database connection */
PGresult *res; /* holds query result */
int i;

conn = PQconnectdb("dbname=postgres"); /* connect to the database */

if (PQstatus(conn) == CONNECTION_BAD) /* did the database connection fail
? */
fprintf(stderr, "Connection to database failed.\n");
fprintf(stderr, "%s", PQerrorMessage(conn));

printf("Enter a max bw: "); /* prompt user for a max_bw */
scanf("%2d", entered_bw);

sprintf(query_string, /* create an SQL query string */
"SELECT entered_bw\
FROM ted_3 \
WHERE max_bw = '%d'", entered_bw);

res = PQexec(conn, query_string); /* send the query */

if (PQresultStatus(res) != PGRES_TUPLES_OK) /* did the query fail? */
fprintf(stderr, "SELECT query failed.\n");


for (i = 0; i < PQntuples(res); i++) /* loop through all rows returned */
printf("%s\n", PQgetvalue(res, i, 0)); /* print the value returned */

PQclear(res); /* free result */

PQfinish(conn); /* disconnect from the database */

return 0;

My thinking is database (odbc) connection is not there it seems , thats y its givining proper result .
so how to establish odbc connection?

Jan 10 '07 #1
1 3371
534 Expert 512MB
Check your code against the Postgres manual:

This url is for ver.8, you can also look at the main doc entry -
- and choose a different version. Make a bookmark, you'll need these docs in the future.

In the paragraph Database Connection Control Functions
pay attention to PQsetdbLogin and PQsetdb in the code snippets.

You have dbname, but you may also need to specify host, port, password, etc for your connection to work.

Then, if you want to see whether you can establish a database connection strip off all non-essential code, and use a hard-coded query; something simple like select version() would be a good thing to start with.
Jan 11 '07 #2

Post your reply

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

Similar topics

2 posts views Thread by Robert | last post: by
reply views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.