Chapter 10. The PostgreSQL C++ API - libpq++

You can build PostgreSQL client applications using a variety of programming languages. In Chapter 8, "The PostgreSQL C API?libpq (Client Applications)," and Chapter 9, "A Simpler C API?libpgeasy," you looked at two of the APIs that you can conveniently use from a C program (libpq and libpgeasy). This chapter introduces you to the libpq++ API. libpq++ is an API designed for use from within a C++ client application. To demonstrate the capabilities provided by libpq++, you'll build a number of client applications in this chapter:

  • client1? A simple example that shows how to connect a C++ application to a PostgreSQL database.

  • client2? Next I'll show you how to catch runtime errors that might occur when you are using libpq++.

  • qt-query? After you know how to intercept and respond to error conditions, you'll build a graphical client (using the Qt GUI toolkit) that will process a single SQL command and display the results in a form that is (hopefully) more attractive than a simple text-based interface.

  • qt-sql? The last client presented in this chapter combines Qt and libpq++ to provide a graphical interactive query processor.

I mentioned in the previous chapter that the libpgeasy API is a wrapper around libpq. The same is true for libpq++?libpq++ is implemented using libpq.

When you use the libpq or libpgeasy APIs, you use a collection of data types (PGresult *, PGconn *, and so on) and functions (PQconnectdb(), PQexec(), and so on) to perform server operations and obtain results. In contrast, when you use the libpq++ API, you use a small collection of classes. The difference between the two approaches can affect the way you think about solving a particular problem. In a function+data type architecture (such as libpq or libpgeasy), you are working with data types that are somewhat independent from the functions that operate on those types. When you use a class- (or more precisely object-) oriented architecture, you define a set of classes that contain both state and behavior. An object is an instance of a class. Its data members represent the state of an object and the behavior is supplied by its member functions[1].

[1] If you are a die-hard C programmer (like me), think of a class as a typedef, an object as a variable whose type is the class; data members as…well, data members; and member functions as function pointers stored within a structure. The analogies aren't perfect, and a C++ purist would probably condemn my ancestors and descendants for suggesting them, but I found the comparisons useful when I cut my first C++ teeth.

    Part II: Programming with PostgreSQL