PostgreSQL

前提条件

PostgreSQLをインストールして、インクルードとライブラリを使用可能にする


サンプルソース

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "libpq-fe.h"
  4.  
  5. static void exit_nicely(PGconn *conn);
  6.  
  7. int main(void){
  8.  
  9. const char *conninfo = "host=localhost user=postgres password=password dbname=testdb1";
  10. PGconn *conn;
  11. PGresult *res;
  12. int nFields;
  13. int i,j;
  14.  
  15. /* データベースとの接続を確立する */
  16. conn = PQconnectdb(conninfo);
  17.  
  18. /* バックエンドとの接続確立に成功したかを確認する */
  19. if (PQstatus(conn) != CONNECTION_OK){
  20. fprintf(stderr, "Connection to database failed: %s",
  21. PQerrorMessage(conn));
  22. exit_nicely(conn);
  23. }
  24.  
  25. /* トランザクションブロックを開始する。 */
  26. res = PQexec(conn, "BEGIN");
  27. if (PQresultStatus(res) != PGRES_COMMAND_OK)
  28. {
  29. fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
  30. PQclear(res);
  31. exit_nicely(conn);
  32. }
  33.  
  34. /*
  35.   * 不要になったら、メモリリークを防ぐためにPGresultをPQclearすべき。
  36.   */
  37. PQclear(res);
  38.  
  39. /*
  40.   * データベースのシステムカタログpg_databaseから行を取り出す。
  41.   */
  42. res = PQexec(conn, "DECLARE myportal CURSOR FOR select * from testtable1");
  43. if (PQresultStatus(res) != PGRES_COMMAND_OK)
  44. {
  45. fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(conn));
  46. PQclear(res);
  47. exit_nicely(conn);
  48. }
  49. PQclear(res);
  50.  
  51. res = PQexec(conn, "FETCH ALL in myportal");
  52. if (PQresultStatus(res) != PGRES_TUPLES_OK)
  53. {
  54. fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(conn));
  55. PQclear(res);
  56. exit_nicely(conn);
  57. }
  58.  
  59. /* まず属性名を表示する。 */
  60. nFields = PQnfields(res);
  61. for (i = 0; i < nFields; i++){
  62. printf("%-15s", PQfname(res, i));
  63. }
  64. printf("\n\n");
  65.  
  66. /* そして行を表示する。 */
  67. for (i = 0; i < PQntuples(res); i++) {
  68. for (j = 0; j < nFields; j++) {
  69. printf("%-15s", PQgetvalue(res, i, j));
  70. }
  71. printf("\n");
  72. }
  73.  
  74. PQclear(res);
  75.  
  76. /* ポータルを閉ざす。ここではエラーチェックは省略した… */
  77. res = PQexec(conn, "CLOSE myportal");
  78. PQclear(res);
  79.  
  80. /* トランザクションを終了する */
  81. res = PQexec(conn, "END");
  82. PQclear(res);
  83.  
  84. /* データベースとの接続を閉じ、後始末を行う。 */
  85. PQfinish(conn);
  86.  
  87. return 0;
  88. }
  89.  
  90. static void exit_nicely(PGconn *conn){
  91. PQfinish(conn);
  92. exit(1);
  93. }
  94.  
  95.  
  96.  

コンパイル・実行

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>
 




最終更新:2010年06月25日 21:46