Client 2—Adding Error Checking

Now let's add a little error-handling code to the client:

/* client2a.c   */

#include <stdlib.h>
#include <libpq-fe.h>
#include <libpgeasy.h>

int main( int argc, char * argv[] )
{
  PGconn *  connection;

  connection = connectdb( argv[1] ? argv[1] : "" );

  if( PQstatus( connection ) != CONNECTION_OK )
    printf( "Caught an error: %s\n", PQerrorMessage( connection ));
  else
    printf( "connection ok\n" );

  disconnectdb();

  exit( EXIT_SUCCESS );
}

This time around, I captured the PGconn * returned by connectdb(). Remember that this PGconn * is the same type of object that you would find in a libpq application. Call the PQstatus() function to determine whether the connection attempt succeeded or failed. If a failure occurs, this ...

Get PostgreSQL, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.