On May 7, 2010, at 10:18 AM, Joao Ferreira gmail wrote:
> Hello all,
>
> I need to write an application in C to read the list of databases
> currently in the server. very much like a "psql -l"...
>
> but I need it in C ! I never used C before to access PG.
>
> the libpq API seems a bit scary !
It's easier than it looks, really:
PGconn *db;
PGresult *result;
int i;
db = PQconnectdb("host=127.0.0.1 dbname=template1 user=joao password=foo");
if(0 == db || PQstatus(db) != CONNECTION_OK) {
fprintf(stderr, "Failed to connect to db: %s", db ? PQerrorMessage(db) : "unknown error\n");
exit(1);
}
result = PQexec(db, "select datname from pg_catalog.pg_database");
if(0 == result || PQresultStatus(result) != PGRES_TUPLES_OK) {
fprintf(stderr, "Failed to run query: %s", result ? PQresultErrorMessage(result) : "unknown error\n");
exit(1);
}
for(i=0; i < PQntuples(result); ++i) {
printf("%s\n", PQgetvalue(result, i, 0));
}
PQclear(result);
PQfinish(db);
(Untested)
> Is there anything, shipped with
> postgresql, other than libpq that would make my life simpler ?
Not for C, I don't think. Other languages (C++, perl ...) have bindings that simplify some things.
Cheers,
Steve