/* beers.c */ /* CMPS180 Project Part 5 Sample Program */ /* Accesses Beers Data Base */ #include #include #include int display_result( PGresult *res ); int main() { PGconn *dbconnection = NULL; PGresult *res; /* first try to establish connection to DB and check for errors */ dbconnection = PQconnectdb("host=localhost dbname=test user=xyz"); if (PQstatus( dbconnection ) == CONNECTION_BAD) { fprintf( stderr, "No connection: %s", PQerrorMessage( dbconnection )); return EXIT_FAILURE; } /* attempt to execute a query */ res = PQexec( dbconnection, "SELECT * from category"); /* check for results */ if (!res) { printf("Query failed\n"); } else if (PQresultStatus( res ) == PGRES_TUPLES_OK){ printf("The following data was returned:\n"); display_result( res ); } else { printf("Query failed, code: %s, mess: %s\n", PQresStatus(PQresultStatus(res)), PQresultErrorMessage(res)); } /* clean up */ if (res) PQclear(res); if ( dbconnection == NULL) return EXIT_FAILURE; PQfinish( dbconnection ); return EXIT_SUCCESS; } /* display a result set */ /* this is the easy way to print a result set if */ /* you don't want to use a cursor and do more */ int display_result( PGresult *res ) { PQprintOpt print_opts; FILE *out_stream = fopen( "/dev/tty", "w" ); if (out_stream == NULL) { return 0; } /* set up print options or use defaults */ memset( &print_opts, '\0', sizeof( print_opts )); print_opts.header = 1; print_opts.align = 1; print_opts.html3 = 0; print_opts.fieldSep = "|"; /* print out the result set */ PQprint( out_stream, res, &print_opts ); return 1; }