Contents
libpq
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!
- PostgreSQL 14
in_hot_standby
now reported byPQparameterStatus()
(commit bf8a662c)- pipeline mode added (commit acb7e4eb)
PQtrace()
output format improved (commit 198b3716)options
read-only
,primary
,standby
, andprefer-standby
added totarget_session_attrs
(commit ee28cacf)- Server Name Indication (SNI) set by default for SSL connections (commit 5c55dc8b)
- deprecated connection parameters
authtype
andtty
removed (commit 14d9b376)
- PostgreSQL 10
passfile
connection parameter added (commit ba005f19)target_session_attrs
connection parameter added (commit 721f7bd3)
- PostgreSQL 9.2
PQsetSingleRowMode()
added (commit ea56ed9a)
- PostgreSQL 9.1
client_encoding
connection parameter added (commit 02e14562)
- PostgreSQL 9.0
application_name
connection parameter added (commit 3dfcf8cc)
- PostgreSQL 8.0
Examples
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.
References
- PostgreSQL documentation: libpq - C Library
- PostgreSQL documentation: libpq environment variables