Client 2—Adding Error Checking
The client1.c application discussed has a fundamental flaw—there is no way to tell whether the connection attempt was successful. This next program attempts a connection and displays an error message if the attempt fails:
1 /* 2 ** File: client2.c 3 */ 4 5 #include <stdlib.h> 6 #include <libpq-fe.h> 7 8 int main( int argc, char * argv[] ) 9 { 10 PGconn * connection; 11 12 if( argc != 2 ) 13 { 14 printf( "usage : %s \"connection-string\"\n", argv[0] ); 15 printf( "example: %s \"user=myname password=cows\"\n", argv[0]); 16 exit( 1 ); 17 } 18 19 if(( connection = PQconnectdb( argv[1] )) == NULL ) 20 { 21 printf( "Fatal error - unable to allocate connection\n" ); 22 exit( 1 ); 23 } 24 25 if( PQstatus( connection ) ...
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.