7 * Test the C version of libpq, the PostgreSQL frontend library.
14 exit_nicely(PGconn
*conn
)
21 main(int argc
, char **argv
)
31 * If the user supplies a parameter on the command line, use it as the
32 * conninfo string; otherwise default to setting dbname=postgres and using
33 * environment variables or defaults for all other connection parameters.
38 conninfo
= "dbname = postgres";
40 /* Make a connection to the database */
41 conn
= PQconnectdb(conninfo
);
43 /* Check to see that the backend connection was successfully made */
44 if (PQstatus(conn
) != CONNECTION_OK
)
46 fprintf(stderr
, "Connection to database failed: %s",
47 PQerrorMessage(conn
));
52 * Our test case here involves using a cursor, for which we must be inside
53 * a transaction block. We could do the whole thing with a single
54 * PQexec() of "select * from pg_database", but that's too trivial to make
58 /* Start a transaction block */
59 res
= PQexec(conn
, "BEGIN");
60 if (PQresultStatus(res
) != PGRES_COMMAND_OK
)
62 fprintf(stderr
, "BEGIN command failed: %s", PQerrorMessage(conn
));
68 * Should PQclear PGresult whenever it is no longer needed to avoid memory
74 * Fetch rows from pg_database, the system catalog of databases
76 res
= PQexec(conn
, "DECLARE myportal CURSOR FOR select * from pg_database");
77 if (PQresultStatus(res
) != PGRES_COMMAND_OK
)
79 fprintf(stderr
, "DECLARE CURSOR failed: %s", PQerrorMessage(conn
));
85 res
= PQexec(conn
, "FETCH ALL in myportal");
86 if (PQresultStatus(res
) != PGRES_TUPLES_OK
)
88 fprintf(stderr
, "FETCH ALL failed: %s", PQerrorMessage(conn
));
93 /* first, print out the attribute names */
94 nFields
= PQnfields(res
);
95 for (i
= 0; i
< nFields
; i
++)
96 printf("%-15s", PQfname(res
, i
));
99 /* next, print out the rows */
100 for (i
= 0; i
< PQntuples(res
); i
++)
102 for (j
= 0; j
< nFields
; j
++)
103 printf("%-15s", PQgetvalue(res
, i
, j
));
109 /* close the portal ... we don't bother to check for errors ... */
110 res
= PQexec(conn
, "CLOSE myportal");
113 /* end the transaction */
114 res
= PQexec(conn
, "END");
117 /* close the connection to the database and cleanup */