Re: list of databases in C ? libpq ? - Mailing list pgsql-general

From Steve Atkins
Subject Re: list of databases in C ? libpq ?
Date
Msg-id E4AEFEF5-7523-4D6A-A238-0BB57786E761@blighty.com
Whole thread Raw
In response to list of databases in C ? libpq ?  (Joao Ferreira gmail <joao.miguel.c.ferreira@gmail.com>)
List pgsql-general
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



pgsql-general by date:

Previous
From: Steve Clark
Date:
Subject: Re: postgreSQL not working after upgrade to Ubuntu 10.4
Next
From: Yeb Havinga
Date:
Subject: Re: postgreSQL not working after upgrade to Ubuntu 10.4