4
* Test the C version of libpq, the PostgreSQL frontend library.
11
exit_nicely(PGconn *conn)
18
main(int argc, char **argv)
28
* If the user supplies a parameter on the command line, use it as the
29
* conninfo string; otherwise default to setting dbname=template1 and
30
* using environment variables or defaults for all other connection
36
conninfo = "dbname = template1";
38
/* Make a connection to the database */
39
conn = PQconnectdb(conninfo);
41
/* Check to see that the backend connection was successfully made */
42
if (PQstatus(conn) != CONNECTION_OK)
44
fprintf(stderr, "Connection to database failed: %s",
45
PQerrorMessage(conn));
50
* Our test case here involves using a cursor, for which we must be
51
* inside a transaction block. We could do the whole thing with a
52
* single PQexec() of "select * from pg_database", but that's too
53
* trivial to make a good example.
56
/* Start a transaction block */
57
res = PQexec(conn, "BEGIN");
58
if (PQresultStatus(res) != PGRES_COMMAND_OK)
60
fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
66
* Should PQclear PGresult whenever it is no longer needed to avoid
72
* Fetch rows from pg_database, the system catalog of databases
74
res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from pg_database");
75
if (PQresultStatus(res) != PGRES_COMMAND_OK)
77
fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
83
res = PQexec(conn, "FETCH ALL in myportal");
84
if (PQresultStatus(res) != PGRES_TUPLES_OK)
86
fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
91
/* first, print out the attribute names */
92
nFields = PQnfields(res);
93
for (i = 0; i < nFields; i++)
94
printf("%-15s", PQfname(res, i));
97
/* next, print out the rows */
98
for (i = 0; i < PQntuples(res); i++)
100
for (j = 0; j < nFields; j++)
101
printf("%-15s", PQgetvalue(res, i, j));
107
/* close the portal ... we don't bother to check for errors ... */
108
res = PQexec(conn, "CLOSE myportal");
111
/* end the transaction */
112
res = PQexec(conn, "END");
115
/* close the connection to the database and cleanup */