実践Linux TOPへ Cプログラミング目次へ
postgreSQL接続 2009年5月更新
●共通Makefile
プログラムソースをsqll.cで保存して、Makefileを以下の内容で準備し、makeを実行する。
字下げはTabキーで行うこと。
# Makefile for sqll
CC = gcc
TARGETS = sqll
OBJ = ${SRC:.c=.o}
SRC = sqll.c
$(TARGETS):${OBJ}
${CC} ${OBJ} -o ${TARGETS} -lpq
${OBJ}:${SRC}
${CC} ${SRC} -c -o ${OBJ} -I /usr/include -I /usr/include/pgsql/server
clean:
rm -f *.o $(TARGETS)
●select
/* ヘッダファイル取り込み */
#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 *sql;
int i, j, fc, rc;
PGconn *con;
PGresult *res;
/* DBとの接続 */
con = PQconnectdb(“hostaddr=’127.0.0.1’ dbname=’zaiko’ user=’zaiko’ password=’yamzaiko’”);
if ( PQstatus(con) == CONNECTION_BAD ) { /* 接続が失敗したときのエラー処理 */
fprintf(stderr,”Connection to database ‘%s’ failed.\n”, “zaiko”);
fprintf(stderr,”%s”,PQerrorMessage(con));
exit(1);
}
/* select文の発行 */
sql = “SELECT * FROM test”;
res = PQexec(con,sql);
if (PQresultStatus(res) != PGRES_TUPLES_OK) { /* SQLの実行に失敗したときのエラー処理 */
fprintf(stderr,”%s”,PQerrorMessage(con));
exit(1);
}
rc = PQntuples(res); //レコード数の取得
fc = PQnfields(res); //フィールド数
char *fn[fc];
printf(“--------------------------------------\n”);
for(i = 0; i < fc ;i++) {
fn[i] = PQfname(res, i); //フィールド名
printf(“%s “,fn[i]);
}
printf(“\n”);
printf(“--------------------------------------\n”);
char *kou[rc];
for(i = 0; i < rc ;i++) {
for(j = 0; j < fc ;j++) {
kou[j] = PQgetvalue(res,i,j);
printf(“%s “,kou[j]);
}
printf(“\n”);
}
PQclear(res);
PQfinish(con);
}
●insert
/* ヘッダファイル取り込み */
#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 sql[255];
int i;
PGconn *con;
PGresult *res;
/* DBとの接続 */
con = PQconnectdb(“hostaddr=’127.0.0.1’ dbname=’zaiko’ user=’zaiko’ password=’yamzaiko’”);
if ( PQstatus(con) == CONNECTION_BAD ) { /* 接続が失敗したときのエラー処理 */
fprintf(stderr,”Connection to database ‘%s’ failed.\n”, “zaiko”);
fprintf(stderr,”%s”,PQerrorMessage(con));
exit(1);
}
/* insert文の発行 */
sprintf(sql,”INSERT INTO test VALUES (‘1-004’,’ddd’,’400’)”);
res = PQexec(con,sql);
if (PQresultStatus(res) != PGRES_COMMAND_OK) { /* SQLの実行に失敗したときのエラー処理 */
fprintf(stderr,”%s”,PQerrorMessage(con));
exit(1);
}
PQclear(res);
PQfinish(con);
}
TOPへ Cプログラミング目次へ