Ubuntu server11.04上にインスールしたPostgreSqlに、C言語でアクセスしてみたいと思います。

  • 以下の記事から、テストデータ作成、テストプログラムをとても参考にさせていただきました。
PostgreSQLをプログラムで操作する
http://www.atmarkit.co.jp/flinux/rensai/postgres03/postgres03.html#3

環境構築

C言語からPostgreSqlを操作するにはlibpqというパッケージが必要みたい。

libpqで検索

$ sudo aptitude search libpq
p   libpq-dev                       - header files for libpq5 (PostgreSQL librar
i A libpq5                          - PostgreSQL C client library
p   libpqxx-2.6.9ldbl               - C++ library to connect to PostgreSQL
p   libpqxx-2.6.9ldbl-dbg           - C++ library to connect to PostgreSQL (debu
p   libpqxx-3.0                     - C++ library to connect to PostgreSQL
p   libpqxx-3.0-dbg                 - C++ library to connect to PostgreSQL (debu
p   libpqxx-dev                     - C++ library to connect to PostgreSQL (deve
p   libpqxx-doc                     - C++ library to connect to PostgreSQL (docu
p   libpqxx3-dev                    - C++ library to connect to PostgreSQL (deve
p   libpqxx3-doc                    - C++ library to connect to PostgreSQL (docu
 
libpq5がPostgreSqlと一緒にインストールされたみたい。
でも必要なのはきっとlibpq-dev

libpq-devインストール

$ sudo aptitude install libpq-dev
 

ヘッダファイル確認

ディレクトリ /usr/include/postgresql/ に件のヘッダファイルがインストールされるみたい。
$ ll /usr/include/postgresql/
total 176
drwxr-xr-x  8 root root  4096 2011-09-29 20:51 ./
drwxr-xr-x 41 root root  4096 2011-09-29 20:51 ../
drwxr-xr-x  2 root root  4096 2011-09-29 20:51 catalog/
-rw-r--r--  1 root root 24635 2012-06-04 13:09 c.h
drwxr-xr-x  3 root root  4096 2011-09-29 20:51 internal/
drwxr-xr-x  2 root root  4096 2011-09-29 20:51 libpq/
-rw-r--r--  1 root root  2270 2012-06-04 13:09 libpq-events.h
-rw-r--r--  1 root root 19646 2012-06-04 13:09 libpq-fe.h
drwxr-xr-x  2 root root  4096 2011-09-29 20:51 mb/
drwxr-xr-x  2 root root  4096 2011-09-29 20:51 nodes/
-rw-r--r--  1 root root 24844 2012-06-04 13:09 pg_config.h
-rw-r--r--  1 root root  7583 2012-06-04 13:09 pg_config_manual.h
-rw-r--r--  1 root root  1111 2012-06-04 13:09 pg_config_os.h
-rw-r--r--  1 root root   349 2012-06-04 13:09 pg_trace.h
-rw-r--r--  1 root root 13126 2012-06-04 13:09 port.h
-rw-r--r--  1 root root  1837 2012-06-04 13:09 postgres_ext.h
-rw-r--r--  1 root root   790 2012-06-04 13:09 postgres_fe.h
-rw-r--r--  1 root root 20694 2012-06-04 13:09 postgres.h
drwxr-xr-x  2 root root  4096 2011-09-29 20:51 utils/
 

テストデータ作成

ユーザテーブル作成

$ psql chapatidb
chapatidb=# create table users (id bigint, name varchar(50), email varchar(50));
CREATE TABLE
 

読み込むテキスト作成 user.txt

値の間の空白はタブです
$ cat users.txt
1	ちゃぱてぃ	chapati@example.com
2	ぶるーべれー	blue@example.com
3	かぼちゃパイ	kabocha@example.com
 

テキスト読み込み

\copyコマンドで、テキストファイルをDBに読み込めるようです。
$ psql chapatidb
chapatidb=# \copy users from users.txt

読み込み結果確認

chapatidb=# select * from users;
 id |     name     |        email
----+--------------+---------------------
  1 | ちゃぱてぃ   | chapati@example.com
  2 | ぶるーべれー | blue@example.com
  3 | かぼちゃパイ | kabocha@example.com
(3 rows)
 

テストプログラム作成、コンパイル、実行

pgtest.c作成 pgtest.c

PostgreSQLをプログラムで操作する
http://www.atmarkit.co.jp/flinux/rensai/postgres03/postgres03.html#3

上記のC言語サンプルをテーブル名等リテラルだけ変更しました。

/* ヘッダファイル取り込み */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#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);
 
}
 

コンパイル

-Iオプションでヘッダファイルの場所を指定して、-lpqでPostgreSqlライブラリの使用を明示しているのかな?
$ gcc pgtest.c -I/usr/include/postgresql -lpq
 

実行

すごいです、動きました。
$ ./a.out
id name email
--------------------------------------
1 ちゃぱてぃ chapati@example.com
2 ぶるーべれー blue@example.com
3 かぼちゃパイ kabocha@example.com
 

タグ:

C言語 PostgreSql
最終更新:2012年09月24日 02:20
添付ファイル