void main vs. int main

어느 것이 옳은 쓰임일까?

잘 설명한 글이 있어서 링크 남김.
내용은 여기.

by soohah | 2009/11/18 15:27 | 트랙백 | 덧글(4)

[2] 간단한 ESQL문장 사용하기

tibero(티베로) tbESQL tutorial 002




DB로 연결하기

모든 DB client program을 실행하기 위해서 가장 먼저 할 일은 DB server로의 연결을 확보하는 일이다.
이 때 사용되는 것이 CONNECT 문장이며, 사용법은 다음과 같다.

EXEC SQL CONNEXT { :user IDENTIFIED BY :pass }
[[ AT { dbname | :host_variable } ] USING :connect_string ] ;


예제를 보자. 흔히 쓰이는 방법이 다음의 두 가지 이다.

    char *conn_str = "tibero/tmax";

    EXEC SQL CONNECT :conn_str;

    char *user_str = "tibero";
    char *pass_str = "tmax";

     EXEC SQL CONNECT :user_str IDENTIFIED BY :pass_str;

DB에 tibero라는 user로 접속하기 위한 문장이다. password는 tmax이다.
user name과 password를 한 변수에 함께 쓰려면 위의 예와 같이 '/'로 구분할 수 있다.

AT 절이나 USING 절을 사용하는 다른 방법은 나중에 설명하기로 한다.



DDL 사용하기

다음과 같은 file을 작성해서 table을 생성해 보자.

tbesql $ vi test_ddl.tbc

/* test_ddl.tbc */

#include <stdio.h>
#include <string.h>

int main(void)
{  
    char *conn_str = "tibero/tmax";

    /* connection */
    EXEC SQL CONNECT :conn_str;

    if (sqlca.sqlcode == 0)
        printf("Connected.\n");
    else
        return -1;

    /* create table */
    EXEC SQL CREATE TABLE TEST01 (A NUMBER, B VARCHAR(10));

    /* check error code */
    if (sqlca.sqlcode == 0)
        printf("Table has been created.\n");
    else
        printf("Error occurred: %d\n", sqlca.sqlcode);

    return 0;
}  

sqlca는 SQL Communication Area의 약자를 따서 만든 이름이며, structure이다.
이 structure는 program의 수행 결과 등을 알기 위한 용도로 쓰이며, 이 중 sqlcode라는 member변수는 결과 코드 값을 보여준다,
0이면 error가 없이 정상적으로 수행된 것이다.
sqlca의 보다 자세한 쓰임에 대해서도 나중에 설명하겠다.

ESQL에서 DDL을 수행할 때는, 예제와 같이 EXEC SQL을 앞에 붙여서 수행하면 된다.
DDL 문장 자체를 string 변수에 저장하여 사용하는 방법은 나중에 살펴보자.


precompile과 compile을 거쳐 실행해 보자.

tbesql $ tbpc test_ddl

tbESQL Precompiler 4 Trunk

TmaxSoft, Co. Copyright(C) 2001-2009. All rights reserved.


test_ddl.tbc is precompiled successfully!

tbesql $ tbpcc test_ddl

tbesql $ ls
test_ddl    test_ddl.tbc   test_ddl.c

tbesql $ ./test_ddl
Connected.
Table has been created.



INSERT 사용하기

이미 존재하는 table에 데이터를 넣기 위해서는 insert문장을 사용해야 하므로, 다음과 같은 file을 작성해보자.

tbesql $ vi test_insert.tbc

/* test_insert.tbc */

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *conn_str = "tibero/tmax";

    EXEC SQL CONNECT :conn_str;
   
    if (sqlca.sqlcode == 0)
        printf("Connected.\n");
    else
        return -1;

    EXEC SQL INSERT INTO TEST01 VALUES (1, 'Tibero');

    if (sqlca.sqlcode == 0)
        printf("1 row has been inserted.\n");
    else
        printf("Error occurred: %d\n", sqlca.sqlcode);

    return 0;
}

아까 table을 생성하기 위한 SQL을 실행했으므로 정상적으로 실행된다는 가정아래 compile과 실행결과는 다음과 같다.

tbesql $ tbpc test_insert

tbESQL Precompiler 4 Trunk

TmaxSoft, Co. Copyright(C) 2001-2009. All rights reserved.


test_insert.tbc is precompiled successfully!

tbesql $ tbpcc test_insert
tbesql $ ./test_insert
Connected.
1 row has been inserted.

만약에 insert할 테이블이 없다면 다음과 같은 에러가 출력될 것이다.

tbesql $ ./test_insert
Connected.
Error occurred: -8033

-8033 error가 출력되었다. 이 에러가 무엇인지 살펴보기 위해서 tberr라는 명령을 사용할 수 있다.

tbesql $ tberr 8033
/*
 * err:   -8033
 * name:  ERROR_DML_OBJ_NOT_EXIST
 * desc:   Specified schema object was not found.  
 * cause:  The specified schema object does not exist.  
 * action: Check the schema object name.;
 */

object가 존재하지 않아서 발생한 에러라는 것을 알 수 있다.
에러가 발생하면 sqlca.sqlcode를 통해 확인하고 적절한 대처를 해주면 되겠다.

INSERT이외에 UPDATE와 DELETE의 쓰임도 크게 다르지 않다. 문장 앞에 EXEC SQL을 붙여서 사용하면 된다.



SELECT 사용하기

이미 존재하는 row를 가져오기 위해, SELECT를 수행해보자.

tbesql $ vi test_select.tbc

/* test_select.tbc */

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *conn_str = "tibero/tmax";
    char a[11];

    memset(a, 0, sizeof(a));

    EXEC SQL CONNECT :conn_str;

    if (sqlca.sqlcode == 0)
        printf("Connected.\n");
    else
        return -1;

    EXEC SQL SELECT A INTO :a FROM TEST01;

    if (sqlca.sqlcode == 0) {
        printf("1 row has been selected.\n");
        printf("column A: %s\n", a);
    }
    else
        printf("Error occurred: %d\n", sqlca.sqlcode);

    return 0;
}

tbsql(oracle에 sqlplus에 해당하는 실행프로그램) 등에서와는 SELECT 문법이 조금 다름을 볼 수 있다.
일반적인 SELECT 문장은 INTO 절이 없다. PSM(oracle에서는 PL/SQL)에서는 INTO 절을 사용한다.

INTO절에는 C변수가 와야 한다. 앞에는 ':'을 달고.
a는 VARCHAR(10)의 column data를 받아야 하므로 char[10]으로 선언했다.
이러한 C변수를 host 변수, 즉 host variable이라고 한다.
host 변수에 대한 좀 더 자세한 얘기는 다음 편에 다루기로 한다.

아까의 INSERT가 에러없이 수행되었다고 가정하고, 이 SELECT 문장을 수행해보자.
아래와 precompile과 compile을 거쳐 실행한다.

tbesql $ tbpc test_select

tbESQL Precompiler 4 Trunk

TmaxSoft, Co. Copyright(C) 2001-2009. All rights reserved.


test_select.tbc is precompiled successfully!
tbesql $ tbpcc test_select
tbesql $ ./test_select
Connected.
Error occurred: 1403

에러가 발생했다.
그런데 이상하다. 1403은 tberr로 조회가 안된다.

tbesql $ tberr 1403
"1403" is invalid err code

1403은 엄밀히 말하면 oracle의 error code이다. oracle을 사용하던 application이라면 대부분 1403이 숫자에 code로 박혀있기 마련인데, 편의를 위하여 tbESQL에서도 이를 그대로 사용할 수 있게 했다.
1403은 DATA NOT FOUND의 의미를 가진다.

이상한 건 또 있다. 아까 INSERT를 분명히 했는데 왜 row가 하나도 안나오지?
transaction의 종료 없이 program이 끝났기 때문이다. COMMIT이 필요하다.



COMMIT 사용하기

transaction을 control하는 COMMIT, ROLLBACK, SAVEPOINT등의 문장 역시 앞에 EXEC SQL만 붙이면 간단히 사용이 가능하다.

아까의 test_insert.tbc를 다음과 같이 고쳐보자.

/* test_insert.tbc */

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *conn_str = "tibero/tmax";

    EXEC SQL CONNECT :conn_str;

    if (sqlca.sqlcode == 0)
        printf("Connected.\n");
    else
        return -1;

    EXEC SQL INSERT INTO TEST01 VALUES (1, 'Tibero');

    if (sqlca.sqlcode == 0)
        printf("1 row has been inserted.\n");
    else
        printf("Error occurred: %d\n", sqlca.sqlcode);

    EXEC SQL COMMIT;

    if (sqlca.sqlcode == 0)
        printf("Committed.\n");
    else
        printf("Error occurred: %d\n", sqlca.sqlcode);

    return 0;
}

precompile과 compile을 거쳐 실행하면 다음과 같은 결과를 볼 수 있다.
test_insert와 test_select를 차례로 실행했다.

tbesql $ ./test_insert
Connected.
1 row has been inserted.
Committed.
tbesql $ ./test_select
Connected.
1 row has been selected.
column A: 1        

SELECT가 아까와는 달리 error없이 잘 수행되었으며, 결과가 출력된 것을 볼 수 있다.

COMMIT은 다음과 같은 방식으로도 사용할 수 있다.

EXEC SQL COMMIT WORK;

WORK라는 keyword는 아무런 의미를 가지지 않는, 관습적인 쓰임을 지원하기 위한 문법이다. 생략해도 무방하다.

EXEC SQL COMMIT WORK RELEASE;

WORK는 위에 말했던 대로 의미가 없으나, RELEASE는 이후 연결을 끊고 모든 자원을 해제하라는 의미를 가진다.
이 문장이 실행된 후 추가로 ESQL을 실행하기 위해서는 CONNECT 문장을 다시 실행해야 한다.



링크와 펌질 환영. 가져가실 때는 출처를 밝혀주세요.

by soohah | 2009/10/21 11:33 | introduction to tbESQL | 트랙백 | 덧글(0)

[1] tbESQL 시작하기

tibero(티베로) tbESQL tutorial 001



환경변수 확인하기


Tibero가 성공적으로 설치되었다면, $TB_HOME이 잡혀 있을 것이다.
(서버를 비롯한 설치 과정은 생략. 자세한 내용은 http://www.tibero.com을 참조)

tbesql $ echo $TB_HOME
/home/soohah/Work/tibero_trunk3


$PATH에 $TB_HOME/client/bin 이 있는지 확인한다.

tbesql $ echo $PATH
/home/soohah/Work/tibero_trunk3/client/bin:/home/soohah/Work/tibero_trunk3/scripts:/home/soohah/Work/tibero_trunk3/bin:/home/soohah/Work/tibero_trunk3/src/scripts:/home/soohah/Work/tibero_trunk3/tools/bin:/usr/lib/j2se/1.4/bin:/usr/lib/j2se/1.4/include:/usr/local/eclipse:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:


$LD_LIBRARY_PATH(다른 플랫폼이라면 적절한 환경변수)에 $TB_HOME/client/lib 혹은 $TB_HOME/client/lib32 가 잘 들어 있는지 확인한다.

tbesql $ echo $LD_LIBRARY_PATH
/lib:/usr/lib:/usr/lib32:/usr/local/lib:/usr/X11R6/lib/:/home/soohah/Work/tibero_trunk3/client/lib:/home/soohah/Work/tibero_trunk3/tool/lib:/lib:/usr/local/BerkeleyDB.4.5/lib/:


이 세 가지의 환경변수가 잘 설정되어 있다면, tbESQL을 사용하는 데는 문제가 없을 것이다.
잘 설치되었다면 다음과 같이 입력해서 정상적인 출력을 볼 수 있을 것이다.

tbesql $ tbpc
Usage: tbpc [-h] [-v] [options] file...

  -h   show this help.
  -v   show tbESQL version.

Option Name     Description                                                
----------------------------------------------------------------------------
CHAR_MAP        Mapping of character arrays and strings                    
CLOSE_ON_COMMIT Close all cursors on COMMIT                                
CODE            The user language type                                     
CONFIG          The name of user configuration file                        
CPP_SUFFIX      C++ filename suffix of generated code                      
DEF_SQLCODE     Whether precompiler generates SQLCODE macro                
DEFINE          Define name for c preprocessor                             
DYNAMIC         Specify Tibero or ANSI, Oracle Dynamic SQL Semantics       
HOLD_CURSOR     Specifies if the cursors will be holded after closing      
INAME           The name of the input file                                 
INCLUDE         Directory paths for included files                         
LINES           Whether to print #line directives for debugging            
MODE            Code conformance to Tibero or ANSI, Oracle rules           
ONAME           The name of the output file                                
ORACA           Whether to use the oraca sturucture                        
PARSE           Specifies which non-SQL code is parsed                     
PREFETCH        Number of rows pre-fetched at cursor OPEN time             
RELEASE_CURSOR  Specifies if the cursors will be released after closing    
SELECT_ERROR    Control flagging of select errors                          
SQLCHECK        Specifies the type and extent of syntatic and semantic checking
STMT_CACHE_SIZE Size of the statement cache                                
SYS_INCLUDE     Directory paths for system header files                    
THREADS         Indicates multi-threads application                        
TYPE_CODE       Use Tibero or ANSI, Oracle type codes for Dynamic SQL      
UNSAFE_NULL     prevent 1405 error when indicator is not specified         
USERID          Specifies Tibero username and password                 


현재 tbESQL의 버전정보를 알고 싶다면.

tbesql $ tbpc -v

tbESQL Precompiler 4 Trunk rev.43057 on Oct 16 2009 15:50:26

TmaxSoft, Co. Copyright(C) 2001-2009.

Linux soohah-desktop 2.6.24-24-generic #1 SMP Fri Sep 18 16:16:18 UTC 2009 x86_64 GNU/Linux version (little-endian)



Hello world 만들기


그럼 시험삼아 이런 test file을 만들어서 precompile 해보자.

tbesql $ vi test1.tbc

#include <stdio.h>

int main(void)
{
    printf("hello world!\n");

    return 1;
}


파일이 잘 만들어졌는지 확인.

tbesql $ ls
test1.tbc


다음과 같이 precompiler를 실행한다.

tbesql $ tbpc test1.tbc

tbESQL Precompiler 4 Trunk

TmaxSoft, Co. Copyright(C) 2001-2009. All rights reserved.


test1.tbc is precompiled successfully!


결과물은 다음과 같이 생성되어 있을 것이다.

tbesql $ ls
test1.c  test1.tbc


c compile을 하는데는 여러방법이 있겠지만, tbESQL에서는 linux에서의 test목적으로 사용자 편의를 위해 단일 file을 보다 쉽게 compile하기 위해 tbpcc라는 shell을 제공한다.
(tbpcc는 $TB_HOME/client/bin 아래에 있으니 궁금한 사람은 내용을 확인해보자. 그냥 gcc를 이용한 sh일 뿐이다.)
이 때, 파일 이름 중 '.tbc'는 생략하도록.

tbesql $ tbpcc test1
tbesql $


바이너리는 이렇게 생성된다.

tbesql $ ls
test1  test1.c  test1.tbc


뻔하지만 결과를 보면.

tbesql $ ./test1
hello world!

Pro*C/C++가 그렇듯이 *.tbc 안에 EXEC SQL로 시작하는 ESQL문장 따위가 들어 있지 않아도 precompile은 잘 된다.



링크와 펌질 환영. 가져가실 때는 출처를 밝혀주세요.

by soohah | 2009/10/20 10:52 | introduction to tbESQL | 트랙백 | 덧글(0)

◀ 이전 페이지다음 페이지 ▶