User Tools

Site Tools


PostgresQL C client sample

For test purpose or as sample.

pg.c
#include <stdio.h>
#include <stdlib.h>
#include "libpq-fe.h"
 
static void exitNicely(PGconn * conn) {
    PQfinish(conn);
    exit(1);
}
 
int main(int argc, char **argv) {
 
    const char *conninfo = "host=xxxxxxx dbname=xxxxxx user=xxxxxx password=xxxxxxxx";
 
    PGconn *conn = PQconnectdb(conninfo);
 
    if (PQstatus(conn) != CONNECTION_OK) {
        fprintf(stderr, "# connection to database failed: %s\n", PQerrorMessage(conn));
        exitNicely(conn);
    } else {
        fprintf(stderr, "# connection to database successful\n");
    }
 
    const char *req = "SELECT 1 + 1 AS SUM";
    PGresult *res = PQexec(conn, req);
 
    if (PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr, "# request %s failed: %s\n", req, PQerrorMessage(conn));
        PQclear(res);
        exitNicely(conn);
    } else {
        fprintf(stderr, "# request %s successful\n", req);
    }
 
    int nCols = PQnfields(res);
 
    for (int i = 0; i < nCols; i++) {
        char *name = PQfname(res, i);
        printf("# column %d have name %s\n", i, name);
    }
 
    int nRows = PQntuples(res);
    for (int i = 0; i < nRows; i++) {
        char *sum = PQgetvalue(res, i, 0);
        printf("# sum = %s\n", sum);
    }
 
    PQclear(res);
    PQfinish(conn);
    return 0;
}

Out

$ ./pg
# connection to database successful
# request SELECT 1 + 1 AS SUM successful
# column 0 have name sum
# sum = 2