- #include <stdio.h>
- #include <stdlib.h>
- #include "libpq-fe.h"
-
- static void exit_nicely(PGconn *conn);
-
- int main(void){
-
- const char *conninfo = "host=localhost user=postgres password=password dbname=testdb1";
- PGconn *conn;
- PGresult *res;
- int nFields;
- int i,j;
-
- /* データベースとの接続を確立する */
- conn = PQconnectdb(conninfo);
-
- /* バックエンドとの接続確立に成功したかを確認する */
- if (PQstatus(conn) != CONNECTION_OK){
- PQerrorMessage(conn));
- exit_nicely(conn);
- }
-
- /* トランザクションブロックを開始する。 */
- res = PQexec(conn, "BEGIN");
- if (PQresultStatus(res) != PGRES_COMMAND_OK)
- {
- PQclear(res);
- exit_nicely(conn);
- }
-
- /*
- * 不要になったら、メモリリークを防ぐためにPGresultをPQclearすべき。
- */
- PQclear(res);
-
- /*
- * データベースのシステムカタログpg_databaseから行を取り出す。
- */
- res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from testtable1");
- if (PQresultStatus(res) != PGRES_COMMAND_OK)
- {
- PQclear(res);
- exit_nicely(conn);
- }
- PQclear(res);
-
- res = PQexec(conn, "FETCH ALL in myportal");
- if (PQresultStatus(res) != PGRES_TUPLES_OK)
- {
- PQclear(res);
- exit_nicely(conn);
- }
-
- /* まず属性名を表示する。 */
- nFields = PQnfields(res);
- for (i = 0; i < nFields; i++){
- }
-
- /* そして行を表示する。 */
- for (i = 0; i < PQntuples(res); i++) {
- for (j = 0; j < nFields; j++) {
- }
- }
-
- PQclear(res);
-
- /* ポータルを閉ざす。ここではエラーチェックは省略した… */
- res = PQexec(conn, "CLOSE myportal");
- PQclear(res);
-
- /* トランザクションを終了する */
- res = PQexec(conn, "END");
- PQclear(res);
-
- /* データベースとの接続を閉じ、後始末を行う。 */
- PQfinish(conn);
-
- return 0;
- }
-
- static void exit_nicely(PGconn *conn){
- PQfinish(conn);
- }
-
-
-
c:\MinGW>gcc -I"C:\Program Files\PostgreSQL\8.4\include" pgsql_sample01.c -o pgsql_sample01.exe "C:\Program Files\PostgreSQL\8.4\lib\libpq.lib"
c:\MinGW>pgsql_sample01.exe
aaa1 aaa2 aaa3
000000001 aaaaa aaaaaa
000000002 bbbbb bbbbbb
000000003 cccccc cccccc
000000004 dddddd ddddddd
c:\MinGW>