데이터베이스 기술/POSTGRESQL

PostgreSQL을 C언어로 사용해보자.

(주)비트나인 2023. 8. 28. 18:39

 

PostgreSQL을 C언어로 사용해보자.

Postgres 다운로드 페이지에서 실행파일이 아닌 소스코드를 다운로드 받아 C언어로 제작된 Client에서 코딩을 통해 쿼리를 실행 하는 방법에 대해 간단한 예제코드와 함께 알아보자.

(본 과정은 MacOS의 XCode기반으로 진행했습니다.)

환경설정

1. PostgreSQL 소스코드 git clone

터미널에 아래 명령문을 이용하여 소스코드를 가져온다.

 

git clone git@github.com:postgres/postgres.git



2. PostgreSQL 설치

./configure 실행

cd postgres
./configure

 

아래와 같이 메세지가 나온다면 가이드에 따라 ./configure --without-icu 명령어를 실행한다.

configure: error: ICU library not found
If you have ICU already installed, see config.log for details on the
failure.  It is possible the compiler isn't looking in the proper directory.
Use --without-icu to disable ICU support.

./configure --without-icu

 

sudo make install 실행 → 별다른 설정이 없다면, postgres 실행파일은 /usr/local/pqsql 에 저장된다.

sudo make install

 

~/.zshrc 파일에 postgres 환경변수 등록

export PATH=$PATH:/usr/local/pgsql/bin
export LD_LIBRARY_PATH=/usr/local/pgsql/lib

 

3. PostgreSQL 서버실행

Create Database Cluster

initdb -D <Database Cluster 디렉토리>

 

Success 화면이 나오면서 가이드 되는 아래 명령어를 실행하여 PostgreSQL 서버 실행

pg_ctl -D <Database Cluster 디렉토리> -l logfile start

# 서버를 종료하려면 아래 명령어를 사용한다.
# pg_ctl -D ./ stop

 

‘mydb’ 라는 이름의 database 생성

createdb mydb

 

생성한 database를 기반으로 한 interactive terminal 실행 → 'mydb=#’ 라는 명령어 창이 보인다.

psql mydb

mydb=#

# 명령어 창을 종료하려면 아래 명령어를 사용한다.
# mydb=# exit

 

예제 실습

1. 예제 쿼리 실행

유저, 비밀번호 생성

create user myuser with password 'mypassword';

 

테이블 생성

create table my_table (key numeric(2), name varchar(14), age numeric(3));

 

테이블에 데이터 추가

insert into my_table values (01, 'Harry', 20);
insert into my_table values (02, 'Potter', 19);

 

여기서는 my_table에 대한 소유 권한을 myuser에게 임시로 부여하였다.

아래 쿼리를 사용하지 않으려면, 7의 쿼리문 코드에 macOS의 username과 password를 입력한다.

alter table my_table owner to myuser;

 

2. XCode project 생성

새 프로젝트 생성 → command Line Tool

 

Product Name 설정, Language → C 설정 → 프로젝트 생성

XCodeProject → settings → ‘Head Search Path’ 검색 후 ‘/usr/local/pgsql/include’ 설정

‘Other Linker Flags’ 검색 후, '-L/usr/local/pgsql/lib’와 ‘-lpq’ 추가

3. Client 기반 쿼리 호출 코드 작성

main.c 파일에 아래의 예제 코드 작성 및 실행

이 코드는 ‘SELECT * FROM my_table’ 쿼리의 결과를 화면에 출력한다.

#include <libpq-fe.h>
#include <stdio.h>

int main(int argc, const char * argv[]) {
    PGconn *conn;
    PGresult *res;
    char *conninfo;
    char *sql;

    /* 연결 정보 설정 */
    conninfo = "host=localhost dbname=mydb user=myuser password=mypassword";

    /* 연결 열기 */
    conn = PQconnectdb(conninfo);
    if (PQstatus(conn)!= CONNECTION_OK) {
        fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn));
        PQfinish(conn);
        return -1;
    }

    /* SQL 쿼리문 작성 */
    sql = "SELECT * FROM my_table";

    /* 쿼리문 실행 */
    res = PQexec(conn, sql);
    if (PQresultStatus(res)!= PGRES_TUPLES_OK) {
        fprintf(stderr, "Query failed: %s", PQerrorMessage(conn));
        PQclear(res);
        PQfinish(conn);
        return -1;
    }

    /* 결과 출력 */
    for (int i = 0; i < PQntuples(res); i++) {
        for (int j = 0; j < PQnfields(res); j++) {
            printf("%s\\t", PQgetvalue(res, i, j));
        }
        printf("\\n");
    }

    /* 결과 해제 */
    PQclear(res);

    /* 연결 종료 */
    PQfinish(conn);

    return 0;
}

 

4. 결과

1 Harry 20
2 Potter 19



글 : 신예지 책임 ( 비트나인 R&D 기획관리팀 )