PostgreSQL's official application interface library for the C programming language

libpq is the official C application programming interface to PostgreSQL, providing a set of library functions enabling client applications to communicate with a PostgreSQL server.

Other application interfaces such as C++, Perl, Python, Tcl and ECPG, as well as client applications such as psql, are based on libpq and inherit some of its behaviour and environment configuration.

Historical note: the "pq" in libpq derives from PostQUEL (see A Brief History of PostgreSQL).

Change history

Incomplete, work in progress!


The following example code demonstrates how to use libpq to connect to a PostgreSQL server and execute a simple query - "SELECT 'hello world'" - and display the output.

#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
static void exit_nicely(PGconn *conn) { PQfinish(conn); exit(1); } int main(int argc, char **argv) { const char *conninfo; PGconn *conn; PGresult *res; if (argc > 1) conninfo = argv[1]; else conninfo = "dbname=postgres"; /* Connect to the database */ conn = PQconnectdb(conninfo); /* Verify success of database connection */ if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn)); exit_nicely(conn); } /* Execute a simple query and display the results */ res = PQexec(conn, "SELECT 'Hello World'"); printf("%s\n", PQgetvalue(res, 0, 0)); PQclear(res); /* close the connection to the database and cleanup */ PQfinish(conn); return 0; }

Further examples can be found in the PostgreSQL manual and in the directory src/test/examples/ in the PostgreSQL source code distribution.


Application interface