#include #include #include #include #include "postgres.h" #include "libpq-fe.h" /* main処理 */ int main(int argc,char **argv) { /* 変数定義 */ char dbName[255] = "chapatidb"; /* データベース名はハードコーディング */ char sql[255]; int i; PGconn *con; PGresult *res; char *kou1,*kou2,*kou3; /* 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文の発行 */ sprintf(sql,"select * from users"); res = PQexec(con,sql); if (PQresultStatus(res) != PGRES_TUPLES_OK) { /* SQLの実行に失敗したときのエラー処理 */ fprintf(stderr,"%s",PQerrorMessage(con)); exit(1); } printf("id name email\n"); printf("--------------------------------------\n"); for(i = 0; i < 3 ;i++) { kou1 = PQgetvalue(res,i,0); kou2 = PQgetvalue(res,i,1); kou3 = PQgetvalue(res,i,2); printf("%s %s %s\n",kou1,kou2,kou3); } PQclear(res); }