6 * this test program shows to use LIBPQ to make multiple backend
15 exit_nicely(PGconn
*conn1
, PGconn
*conn2
)
25 check_conn(PGconn
*conn
, const char *dbName
)
27 /* check to see that the backend connection was successfully made */
28 if (PQstatus(conn
) != CONNECTION_OK
)
30 fprintf(stderr
, "Connection to database \"%s\" failed: %s",
31 dbName
, PQerrorMessage(conn
));
37 main(int argc
, char **argv
)
54 * PGresult *res1, *res2;
60 fprintf(stderr
, "usage: %s tableName dbName1 dbName2\n", argv
[0]);
61 fprintf(stderr
, " compares two tables in two databases\n");
70 * begin, by setting the parameters for a backend connection if the
71 * parameters are null, then the system will try to use reasonable
72 * defaults by looking up environment variables or, failing that, using
75 pghost
= NULL
; /* host name of the backend server */
76 pgport
= NULL
; /* port of the backend server */
77 pgoptions
= NULL
; /* special options to start up the backend
79 pgtty
= NULL
; /* debugging tty for the backend server */
81 /* make a connection to the database */
82 conn1
= PQsetdb(pghost
, pgport
, pgoptions
, pgtty
, dbName1
);
83 check_conn(conn1
, dbName1
);
85 conn2
= PQsetdb(pghost
, pgport
, pgoptions
, pgtty
, dbName2
);
86 check_conn(conn2
, dbName2
);
88 /* start a transaction block */
89 res1
= PQexec(conn1
, "BEGIN");
90 if (PQresultStatus(res1
) != PGRES_COMMAND_OK
)
92 fprintf(stderr
, "BEGIN command failed\n");
94 exit_nicely(conn1
, conn2
);
98 * make sure to PQclear() a PGresult whenever it is no longer needed to
104 * fetch instances from the pg_database, the system catalog of databases
106 res1
= PQexec(conn1
, "DECLARE myportal CURSOR FOR select * from pg_database");
107 if (PQresultStatus(res1
) != PGRES_COMMAND_OK
)
109 fprintf(stderr
, "DECLARE CURSOR command failed\n");
111 exit_nicely(conn1
, conn2
);
115 res1
= PQexec(conn1
, "FETCH ALL in myportal");
116 if (PQresultStatus(res1
) != PGRES_TUPLES_OK
)
118 fprintf(stderr
, "FETCH ALL command didn't return tuples properly\n");
120 exit_nicely(conn1
, conn2
);
123 /* first, print out the attribute names */
124 nFields
= PQnfields(res1
);
125 for (i
= 0; i
< nFields
; i
++)
126 printf("%-15s", PQfname(res1
, i
));
129 /* next, print out the instances */
130 for (i
= 0; i
< PQntuples(res1
); i
++)
132 for (j
= 0; j
< nFields
; j
++)
133 printf("%-15s", PQgetvalue(res1
, i
, j
));
139 /* close the portal */
140 res1
= PQexec(conn1
, "CLOSE myportal");
143 /* end the transaction */
144 res1
= PQexec(conn1
, "END");
147 /* close the connections to the database and cleanup */