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.
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.
Most languages do this the same way:
With libpq:
#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); }