postgresql-demos/c/postgresql_demo.c

42 líneas
866 B
C

#include <stdio.h>
#include <postgresql/libpq-fe.h>
int main(int argc, char *argv[]) {
PGconn *conn;
PGresult *res;
int i;
int j;
conn = PQsetdbLogin("localhost", "5432", "", "", "database", "user", "password");
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn));
PQfinish(conn);
return 1;
}
res = PQexec(conn, "SELECT * FROM turista");
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
return 1;
}
for (i = 0; i < PQnfields(res); i++) {
printf("%-20s", PQfname(res, i));
}
printf("\n\n");
for (i = 0; i < PQntuples(res); i++){
for (j = 0; j < PQnfields(res); j++) {
printf("%-20s", PQgetvalue(res, i, j));
}
printf("\n");
}
PQclear(res);
PQfinish(conn);
return 0;
}