Fix obsolete comment regarding FSM truncation.
[PostgreSQL.git] / src / test / examples / testlibpq.c
blob1e506d25e8c5e69506720f6a96f3d92dab22c188
1 /*
2 * $PostgreSQL:$
5 * testlibpq.c
7 * Test the C version of libpq, the PostgreSQL frontend library.
8 */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include "libpq-fe.h"
13 static void
14 exit_nicely(PGconn *conn)
16 PQfinish(conn);
17 exit(1);
20 int
21 main(int argc, char **argv)
23 const char *conninfo;
24 PGconn *conn;
25 PGresult *res;
26 int nFields;
27 int i,
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.
35 if (argc > 1)
36 conninfo = argv[1];
37 else
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));
48 exit_nicely(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
55 * a good example.
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));
63 PQclear(res);
64 exit_nicely(conn);
68 * Should PQclear PGresult whenever it is no longer needed to avoid memory
69 * leaks
71 PQclear(res);
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));
80 PQclear(res);
81 exit_nicely(conn);
83 PQclear(res);
85 res = PQexec(conn, "FETCH ALL in myportal");
86 if (PQresultStatus(res) != PGRES_TUPLES_OK)
88 fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
89 PQclear(res);
90 exit_nicely(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));
97 printf("\n\n");
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));
104 printf("\n");
107 PQclear(res);
109 /* close the portal ... we don't bother to check for errors ... */
110 res = PQexec(conn, "CLOSE myportal");
111 PQclear(res);
113 /* end the transaction */
114 res = PQexec(conn, "END");
115 PQclear(res);
117 /* close the connection to the database and cleanup */
118 PQfinish(conn);
120 return 0;