connect, disconnect를 별도의 파일로 분리하기.

이번에는 데이터베이스 접속 정보를 .example.pc 파일로 분리해보도록 하겠습니다.
그래서 파일 구조는 다음과 같습니다.

example.h
example.pc
main.pc --> 여기서 example.pc의 connect_to_db를 사용합니다.


/* example.h */
#ifndef EXAMPLE_H
#define EXAMPLE_H

#include <stdio.h>

void connect_to_db(const char *username, const char *password);
void disconnect_from_db();

#endif



/* example.pc */
#include <stdio.h>
#include <sqlca.h>
#include <string.h>
#include "example.h" /* 헤더 파일 포함 */

/* 데이터베이스 연결 함수 정의 */
void connect_to_db(const char *username, const char *password)
{

    EXEC SQL BEGIN DECLARE SECTION;
    VARCHAR connect_string[200];
    EXEC SQL END DECLARE SECTION;

    strcpy(connect_string.arr, "//localhost:1521/ORCLPDB1");
    connect_string.len = strlen(connect_string.arr);

    EXEC SQL CONNECT : username IDENTIFIED BY : password USING : connect_string;

    if (sqlca.sqlcode == 0)
    {
        printf("Connected to the database.\n");
    }
    else
    {
        printf("Failed to connect to the database. SQLCODE: %d\n", sqlca.sqlcode);
    }
}

/* 데이터베이스 연결 해제 함수 정의 */
void disconnect_from_db()
{
    EXEC SQL COMMIT WORK RELEASE;
    printf("Disconnected from the database.\n");
}



/* main.h */
#include <stdio.h>
#include <sqlca.h>
#include "example.h" /* 외부 함수 선언이 있는 헤더 파일 포함 */

int main() {
    const char *username = "hr";
    const char *password = "password";

    /* DB 연결 */
    connect_to_db(username, password);

    /* DB 연결 해제 */
    disconnect_from_db();

    return 0;
}

빌드 순서

1. proc iname=example.pc
2. proc iname=main.pc
3. gcc example.c main.c -o main_program -L$ORACLE_HOME/lib -lclntsh -I$ORACLE_HOME/precomp/public
4. ./main_program

댓글 쓰기

댓글 목록