LIBPQ++ is POSTGRESQL's C++ interface. Figure
shows our application using this interface.
/*
* libpq++ sample program
*/
#include <iostream.h>
#include <libpq++.h> // libpq++ header file
int main()
{
char state_code[3]; // holds state code entered by user
char query_string[256]; // holds constructed SQL query
PgDatabase data("dbname=test"); // connects to the database
if ( data.ConnectionBad() ) // did the database connection fail?
{
cerr << "Connection to database failed." << endl
<< "Error returned: " << data.ErrorMessage() << endl;
exit(1);
}
cout << "Enter a state code: "; // prompt user for a state code
cin.get(state_code, 3, '\n');
sprintf(query_string, // create an SQL query string
"SELECT name \
FROM statename \
WHERE code = '%s'", state_code);
if ( !data.ExecTuplesOk(query_string) ) // send the query
{
cerr << "SELECT query failed." << endl;
exit(1);
}
for (int i=0; i < data.Tuples(); i++) // loop through all rows returned
cout << data.GetValue(i,0) << endl; // print the value returned
return 0;
}
LIBPQ++ allows database access using object methods rather than function calls.