/* * testlibpq.c * * Test the C version of libpq++, the PostgreSQL frontend * library. * * NOTE: There us PgCursor class which makes more sense to use in this example * (See pgsql/include/libpq++/*.h for classes suported (not many) * */ #include #include void exit_nicely(PgDatabase &conn) { conn.~PgDatabase(); exit(1); } main() { char dbName[32]; char password[32]; char conninfo[128]; int nFields; int i, j; int res; printf("database name: "); scanf("%s", dbName); printf("password: "); scanf("%s", password); sprintf(conninfo, "host = marlowe dbname = %s user = %s password = %s", dbName, dbName, password); /* make a connection to the database */ PgDatabase conn(conninfo); /* * check to see that the backend connection was successfully made */ if (conn.ConnectionBad()) { fprintf(stderr, "Connection to database '%s' failed.\n", dbName); fprintf(stderr, "%s", conn.ErrorMessage()); exit_nicely(conn); } /* debug = fopen("/tmp/trace.out","w"); */ /* PQtrace(conn, debug); */ /* start a transaction block */ res = conn.Exec("BEGIN"); if (res != PGRES_COMMAND_OK) { fprintf(stderr, "BEGIN command failed\n"); exit_nicely(conn); } /* * fetch rows from the pg_database, the system catalog of * databases */ res = conn.ExecCommandOk("DECLARE mycursor CURSOR FOR select * from pg_tables"); if (!res) { fprintf(stderr, "DECLARE CURSOR command failed\n"); exit_nicely(conn); } res = conn.ExecTuplesOk("FETCH ALL in mycursor"); if (!res) { fprintf(stderr, "FETCH ALL command didn't return tuples properly\n"); exit_nicely(conn); } /* first, print out the attribute names */ nFields = conn.Fields(); printf("Number of fields: %d\n", nFields); for (i = 0; i < nFields; i++) printf("%-15s", conn.FieldName(i)); printf("\n\n"); /* next, print out the rows */ for (i = 0; i < conn.Tuples(); i++) { for (j = 0; j < nFields; j++) printf("%-15s", conn.GetValue(i, j)); printf("\n"); } /* close the cursor */ res = conn.Exec("CLOSE mycursor"); /* commit the transaction */ res = conn.Exec("COMMIT"); /* close the connection to the database and cleanup */ /* fclose(debug); */ return 0; }