Client 1 - Connecting to the Server

To start, let's look at a simple example that will make a libpq++ connection to a database server (see Listing 10.1).

Listing 10.1 client1.cpp

/* client1.cpp */

#include <libpq++.h>

#include <iostream.h>

int main( int argc, char * argv[] )


    PgConnection conn( "" );


That's all you need to do to make a connection to the default database server.

There are only two lines of code here that are specific to a libpq++ application. You first include the libpq++.h header file to include libpq++ class definitions (and declarations). Inside the main() function, you instantiate a PgConnection object. The PgConnection constructor uses the connection string that you provide to establish a database connection.

In this example, I provided the PgConnection constructor with an empty connection string?that means that you will make a connection with a default set of connection options. If you want, you can provide a connection string such as

PgConnection conn( "dbname=accounting user=korry password=cows" );

The connection string format may look familiar?the PgConnection constructor accepts the same set of connection options that are used by libpq's PQconnectdb() function, which was discussed in Chapter 8, "The PostgreSQL C API?libpq (Client Applications)."

Notice that I don't have any cleanup code in client1.cpp. The PgConnection constructor takes care of tearing down the server connection when the PgConnection object goes out of scope (at the end of the main() function).

    Part II: Programming with PostgreSQL