Chapter 8. The PostgreSQL C API - libpq

A user interacts with a PostgreSQL database by using an application, but how does an application interact with PostgreSQL? PostgreSQL provides a number of application programming interfaces (or APIs for short). Three of these APIs are designed to be used by applications written in C?libpq, libpgeasy, and ODBC. Each API has advantages and disadvantages. libpgeasy, for example, is very easy to use, but doesn't offer much flexibility. If your application uses the ODBC API, you gain portability at the cost of complexity.

Table 8.1 compares the three C-language APIs offered by PostgreSQL.

Table 8.1. Comparison of C Language APIs for PostgreSQL




RDBMS Portability



Medium to high

PostgreSQL only




PostgreSQL only


Medium to high


Multiple database systems

Notice that an application that uses ODBC to connect to PostgreSQL can connect to other database systems as well.

In this chapter, I'll explain the libpq API. libpq is a set of functions that you can call from a C program to interact with a PostgreSQL server. In later chapters, I will cover libpgeasy and ODBC, as well as a few APIs designed for languages other than C.

The libpq API is used to implement most of the other client APIs. After you understand how to interact with a PostgreSQL server using libpq, you will find that most of the other APIs simply wrap up the libpq API in different flavors. For example, the libpgeasy API combines some of the more common libpq operations into a set of higher-level functions. The libpgeasy functions are easier to use, but you don't have quite as much power and flexibility as you would with a libpq application.

    Part II: Programming with PostgreSQL