6.4 LABORATORY - USING C FOR DATABASE CALLS
The program listing in Figure X.8 can be used to access the Postgres database. It uses a database access library called 'libpq'. This library of functions allows SQL database queries. The results of the query can then be easily retrieved.
In this example the program begins with an attempt to connect to the database using the function 'PQconnectdb', and the status of the connection is then checked using 'PQstatus'. An SQL query is passed to the database using the 'PQexec' command, and the results are returned into the 'PGresult' structured called 'res' in this example. The results can be checked using 'PQresultStatus', and retrieved using the 'PQgetvalue' function. The 'PQntuples' function returns the number of matching results.
After each query the results structure should be released using 'PQclear', and when all database access is complete the connection to the database should be terminated with 'PQfinish'.
Figure X.8 - C Program for Database Access (dbtest.c)
Figure X.9 - Makefile for Database Program
1. Enter the program and makefile given in the Overview section. Use 'make' to compile the program, and run it to verify that it does access the database.