/* showtable.c */ /* ヘッダファイル取り込み */ #include #include #include #include #include "postgres.h" #include "libpq-fe.h" /* main処理 */ int main(int argc,char **argv) { /* 変数定義 */ char dbName[255] = "template1"; /* データベース名はハードコーディング */ char sql[255]; int i, j; PGconn *con; PGresult *res; char *kou; char *tableName; int rowCount = 0; int columnCount = 0; if(argc != 2) { printf("Usage: showtable テーブル名\n"); exit(0); } tableName = argv[1]; /* DBとの接続 */ con = PQsetdb("","",NULL,NULL,dbName); if ( PQstatus(con) == CONNECTION_BAD ) { /* 接続が失敗したときのエラー処理 */ fprintf(stderr,"Connection to database '%s' failed.\n",dbName); fprintf(stderr,"%s",PQerrorMessage(con)); exit(1); } /* select文の発行 */ strcpy(sql , "select * from "); strcat(sql , tableName); printf("%s\n",sql); res = PQexec(con,sql); if (PQresultStatus(res) != PGRES_TUPLES_OK) { /* SQLの実行に失敗したときのエラー処理 */ fprintf(stderr,"%s",PQerrorMessage(con)); exit(1); } rowCount = PQntuples(res); columnCount = PQnfields(res); /* 列名の列挙 */ for(j = 0; j < columnCount; j++) { kou = PQfname(res,j); printf("'%s' ",kou); } printf("\n"); printf("--------------------------------------\n"); /* 値の列挙 */ for(i = 0; i < rowCount ;i++) { for(j = 0; j < columnCount; j++) { kou = PQgetvalue(res,i,j); printf("'%s' ",kou); } printf("\n",kou); } /* カーソルを閉じます */ PQclear(res); /* データベースへの接続を閉じてクリーンアップします */ PQfinish(con); }