C言語でPostgreSQL8.2を操作

2007/10/31,2009/1/21


準備

C言語からpostgresqlを使うために、libpqxxをインストールする。
su -
yum install libpqxx postgresql-devel 

データベースユーザ

最低限の権限を持ったデータベースユーザ(webmaster)を新しく作成する。
データベースユーザをつくるとき、3つの質問がある。これに対して、n,y,nとして答える。
su - postgres
createuser webmaster
  Shall the new role be a superuser? (y/n) n
  Shall the new role be allowed to create databases? (y/n) y
  Shall the new role be allowed to create more new roles? (y/n) n
作成したデータベースユーザ(webmaster)がデータベースにアクセスするためのパスワードを設定する。
データベースのためのパスワードはデータベースが管理する。OSにログインするためのパスワードとは独立した管理になる。
psql
ALTER ROLE webmaster with unencrypted password 'xxxxxx' ;
\q
grep localhost /var/lib/pgsql/data/pg_hba.conf 
/var/lib/pgsql/data/pg_hba.confにlocalhostからのアクセス許可が記述されて入れる(localhost all all trust)ことを確認する。
データベースユーザの設定を有効にするため、PostgreSQLを再起動する。
su -
service postgresql restart

データベース,テーブル,データ

createdb 
psql
create table sample(tel int,name varchar(50));
insert into sample values(6547,'情報通信実験室');
insert into sample values(6447,'高橋研究室');
select * from sample ;
あたらしくデータベース(データベース名webmaster),テーブル(テーブル名sample)を作成し、さらに2レコード分のデータを挿入した。
テーブルを確認するために、select文でテーブルの内容を表示した。

sorce code

~/webmaster以下にtest1.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] = "webmaster"; /* データベース名はハードコーディング */
    char sql[255];
    int i;
    PGconn *con;
    PGresult *res;
    char *kou1,*kou2;

    /* 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 sample");
    res = PQexec(con,sql);
    if (PQresultStatus(res) != PGRES_TUPLES_OK) { /* SQLの実行に失敗したときのエラー処理 */
        fprintf(stderr,"%s",PQerrorMessage(con));
        exit(1);
    }

    printf(" id   nr   name\n");
    printf("--------------------------------------\n");
    for(i = 0; i < 2 ;i++) {
        kou1 = PQgetvalue(res,i,0);
        kou2 = PQgetvalue(res,i,1);
        printf("%s %s\n",kou1,kou2);
    }
    PQclear(res);
  return 0;
}

compile

postgres.h他がない場合は、postgresql-8.2.x.tar.gz(PostgreSQLソースリスト)を展開する。
展開し、postgresql-8.2.x/srcを環境変数POSTGRES_HOMEに設定する。
su - webmaster
export POSTGRES_HOME=~/postgresql-8.2.5/src
gcc -o test1 test1.c -I$POSTGRES_HOME/include -L$POSTGRES_HOME/lib -lpq -lnsl -lcrypt
(簡単なSQL文では、gcc -o test1 test1.c -I$POSTGRES_HOME/include -lpq でも可)

2009/1/21
postgres.h他がない場合は、postgresql-develをインストールする。
su -
yum install postgresql-devel
コンパイル時にpostgres.hを含むディレクトリ(-Iオプション)とpostgresqlライブラリ(-lオプション)を指定する。
ster@vm135 sql]$ gcc -o test1 test1.c -I /usr/include/pgsql/server -lpq

問題点


@IT PostgreSQLをプログラムで操作する