User Tools

Site Tools


programming:c:libpq

PostgreSQL with libpq

libpq is the frontend API for PostgreSQL, written in C. Upstream has fantastic documentation, but the workflows aren't obvious unless you've used other database APIs like PHP's PDO class or the sqlite module in Python. This page will outline a few common tasks and how to do them.

Linking

The -lpq argument to your compiler should be enough. You should already have PostgreSQL server installed (and/or its headers) to link to the library correctly.

Basic Connection

Most languages do this the same way:

  1. attempt to connect
  2. check for an "OK" status
  3. wrap the above in some sort of code block
  4. do your business
  5. close the connection

With libpq:

libpq_conn_demo.c
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
 
int main(int argc, char **argv) {
    // create what we need to connect: the db connection structure and its options
    PGconn *conn;
    const char *dbopts;
 
    // accept an argument on the command line to pass to Postgres
    if (argc > 1) {
        dbopts = argv[1];
    } else {
        dbopts = "dbname = default";
    }
 
    // 1: attempt to connect
    conn = PQconnectdb(dbopts);
    // 2: check for an OK status that is...
    // 3: wrapped in a code block
    if (PQstatus(conn) != CONNECTION_OK) {
        fprintf(stderr, "Connection failed: %s\n", PQerrorMessage(conn));
    } else {
        // 4: do your business
        printf("Connection successful!\n");
    }
    // 5: close the connection
    PQfinish(conn);
    exit(1);
}

References

programming/c/libpq.txt · Last modified: 2018-07-03 01:00 by 127.0.0.1