testlibpq3.cc 1.7 KB
Newer Older
1 2 3 4
/*
 * testlibpq3.cc
 * 	Test the C++ version of LIBPQ, the POSTGRES frontend library.
 *
5 6
 *  queries the template1 database for a list of database names using transaction block
 *  and cursor interface.
7 8 9
 *
 */

10 11
#include <iostream.h>
#include <iomanip.h>
B
Bruce Momjian 已提交
12
#include <libpq++.h>
13

14 15 16 17 18 19 20 21
int main()
{
  // Begin, by establishing a connection to the backend.
  // When no parameters are given then the system will
  // try to use reasonable defaults by looking up environment variables 
  // or, failing that, using hardwired constants.
  // Create a cursor database query object.
  // All queries using cursor will be performed through this object.
22
  const char* dbName = "dbname=template1";
23 24 25 26 27 28 29
  PgCursor cData(dbName, "myportal");

  // check to see that the backend connection was successfully made
  if ( cData.ConnectionBad() ) {
      cerr << "Connection to database '" << dbName << "' failed." << endl
           << "Error returned: " << cData.ErrorMessage() << endl;
      exit(1);
30
  }
31 32 33 34
  
  // submit command to the backend
  if ( !cData.Declare("select * from pg_database") ) {
    cerr << "DECLARE CURSOR command failed" << endl;
35 36 37
    exit(1);
  }

38 39 40
  // fetch instances from the pg_cDatabase, the system catalog of cDatabases
  if ( !cData.Fetch() ) {
    cerr << "FETCH ALL command didn't return tuples properly" << endl;
41 42 43
    exit(1);
  }
 
44 45 46 47 48 49 50
  // first, print out the attribute names
  int nFields = cData.Fields();
  for (int i=0; i < nFields; i++)
      cout << setiosflags(ios::right) << setw(15) << cData.FieldName(i);
  cout << endl << endl;

  // next, print out the instances
51
  for (int i=0; i < cData.Tuples(); i++) {
52 53 54
       for (int j=0; j < nFields; j++)
            cout << setiosflags(ios::right) << setw(15) << cData.GetValue(i,j);
       cout << endl;
55 56
  }
}