Source Code for cities.c
#include <libpq-fe.h>
#include <strings.h>
int
main(int argc, char** argv) {
PGconn* conn;
PGresult* result;
int i;
char* dbname = "tutorial";
conn = PQsetdb(NULL, NULL, NULL, NULL, dbname);
if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr,
"Connection to database '%s' failed.\n", dbname);
fprintf(stderr, "%s", PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
result = PQexec(conn, "select * from cities");
if ((!result) || (PGRES_TUPLES_OK !=
PQresultStatus(result))) {
fprintf(stderr,
"Error sending query.\nDetailed report: %s\n",>
PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
printf("name\t\tpopulation\taltitude\n\n");
for (i = PQntuples(result)-1; i >= 0; i--) {
printf("%s\t%s\t\t%s\n",
PQgetvalue(result,i,0),
PQgetvalue(result,i,1),
PQgetvalue(result,i,2));
}
}
Copyright © 1994 - 2018 Linux Journal. All rights reserved.