database.sarang.net
UserID
Passwd
Database
DBMS
MySQL
ㆍPostgreSQL
Firebird
Oracle
Informix
Sybase
MS-SQL
DB2
Cache
CUBRID
LDAP
ALTIBASE
Tibero
DB 문서들
스터디
Community
공지사항
자유게시판
구인|구직
DSN 갤러리
도움주신분들
Admin
운영게시판
최근게시물
PostgreSQL Devel 3544 게시물 읽기
No. 3544
PostgreSQL 응용 프로그램 작성하기 (V)
작성자
정재익(advance)
작성일
2001-10-18 20:22
조회수
13,096
첨부파일: FinerDetail.zip (7,608bytes)

상세한 설명

 

이번 각각의 단계에 대해서 좀더 상세한 설명을 보도록 하자.

 

. 접속

. 질의

. 결과

 

 

접속

 

여러분들은 접속함수 호출시에 데이터베이스를 명시하는데 사용하는 문자열을 알아야 한다.

 

접속시 필요한 인자에는 다음과 같은 것들이 있다 :

 

. 호스트 이름

. 호스트 주소 (host address)

. 포트 번호

. 접속하고자 하는 디비 이름

. 디비 사용자명

. 디비 사용자 패스워드

 

다른 몇가지 옵션을 더 사용할 수도 있다. 접속 문자열의 형식은 "option=value option=value ...."

이와 같은 형식이다.

예를 들면, billing.bigco.com 에 있는 finance 라는 데이터베이스로 sam 이라는 사용자의 이름으로

접속하고자 한다면 다음과 같은 인수 문자열을 전달해 준다.

 

"host=billing.bigco.com dbname=finance user=sam"

 

접속 함수을 호출한 결과로서 돌아오는 접속 핸들은 질의를 보내기 전에 미리 접속이 제대로 되었는지

확인해 보아야만 한다.

 

 

질의

 

질의는 그냥 일상적인 문자열로서 데이터베이스 서버로 전달 된다는 사실을 알아야 한다. 이것은 대단히

프로그래밍 하기 쉽게 만든다. 여러분들은 손쉽게 질의 문자열을 만듦으로서 질의를 만들수 있다.

다음 예제를 참조하시기 바란다.

 

        char query_string[500];  
        char name[50];  
        int unique_id;  


        sprintf(query_string, "SELECT * FROM tab WHERE col = %d", unique_id); 
        [color=#0000FF]res = PQexec([/color][color=#FF0000]conn[/color][color=#0000FF], query_string);[/color]

또는 

        sprintf(query_string, "INSERT INTO tab VALUES (%d, '%s')", unique_id, name); 
        [color=#0000FF]res = PQexec([/color][color=#FF0000]conn[/color][color=#0000FF], query_string);[/color]

 

좀더 상세한 예제를 이전 장에서 참조할수 있을 것이다.

결과 핸들은 그 결과 값을 참조하기 전에 성공적으로 질의가 수행되었는지 참조해 볼 필요성이 있다.

마지막 질의에서, name 은 문자열 변수이다. 만일 단일 따옴표를 포함한다면 이들 문자는

역슬래쉬-단일따옴표(') 또는 두개의 단일따옴표('')로 변경해 주어야 한다. 만약 name 내에

역슬래쉬(\)를 포함한다면 이것은 두개의 역슬래쉬(\)로 바꾸어 주어야 한다.

 

 

결과

 

질의의 결과를 조회하는 것은 단순하고 공식적이다. 우선 SELECT 만이 결과집합 (result set) 을 돌려 준다.

INSERT 나 DELETE 같은 명령어들은 단순히 상태 정보만을 돌려 준다. SELECT 의 result set 은 row 와

column 으로 이루어 진 table 이다. 물론 때로는 결과로서 오로지 한 column 과 한 row 만이 돌아 오는

경우도 있으나 이것도 역시 Table 로서 접근해야 한다. 다음 명령어가 첫 행의 첫 컬럼을 조회하는 방법이다.

 

         printf("%s\n", [color=#00FF00]PQgetvalue([/color][color=#0000FF]res[/color][color=#00FF00], 0, 0)[/color]);   

 

첫행 과 첫 컬럼은 번호를 0 (zero)으로 부여한다. libpq 에서 PQntuples() 함수는 result 로 돌아온 row 의

수를 돌려준다. 그리고, PQnfields() 함수는 결과로 돌아온 column 의 수를 돌려 준다. 이들 값을

이용하여 결과값으로 부터 특정 row 와 column 를 조회할 수 있다.

다음은 결과값을 돌아온 모든

줄을 조회하는 좀더 복잡한 예제이다.

 

        int i, j;  
          
        for (i = 0; i < [color=#00FF00]PQntuples([/color][color=#0000FF]res[/color][color=#00FF00])[/color]; i++)                /* loop through all rows returned */ 
            for (j = 0; j < [color=#00FF00]PQnfields([/color][color=#0000FF]res[/color][color=#00FF00], 0, 0)[/color]; j++)                /* loop through all columns 
                printf("%s\n", [color=#00FF00]PQgetvalue([/color][color=#0000FF]res[/color][color=#00FF00], i, j)[/color]);          /* print the value returned */ 

 

Binary cursor 를 사용하지 않는한, 모든 결과는 ASCII 문자열로서 돌아온다. 만약 여러분들이 만든

응용프로그램 내에서 다른 형식이 필요하다면, 그 값은 응용프로그램 내부에서 직접 변환을 시켜야 한다.

PostgreSQL 인터페이스에는 유용한 정보를 돌려 주는 좀더 다양한 함수들이 존재한다.

 

o Result status
  . error messages strings associated with connection and result handles 

o SELECT result information 
  . number of rows returned 
  . number of columns returned 
  . column names associated with result column numbers 
  . column numbers associated with result column names 
  . column data types 
  . column data type modifiers 
  . column length 
  . cursor binary status 

o SELECT values 
 . value null status 
 . value length 

o Non-SELECT result information 
  . command status strings 
  . OID of inserted rows

 

 

결론

 

이 글은 응용프로그램 내에서 PostgreSQL 을 어떻게 이용할 것인가 하는 방법에 대해 설명해 놓은 것이다.

 

. 접속 요청을 하고 connection 핸들을 얻는다

. 질의를 보내고, result 핸들을 얻는다

. 결과 값을 조회한다

 

이 글은 단지 두가지 프로그래밍 언어만으로 응용 프로그램을 만드는 방법에 대해 적어 놓았다.

그러나 다른 프로그래밍 언어에서 응용프로그램을 만드는 것도 똑같은 개념을 사용한다. 다른 여러가지

프로그래밍 언어로서 작성된 같은 응용 프로그램을 저자가 지은 책 PostgreSQL: Introduction and Concepts

(http://www.postgresql.org/docs/programmer/programmer.html) 에서 찾을 수 있다. 좀더 자세한

프로그래밍 언어에 대한 인터페이스들은 PostgreSQL Programmer's Manual 에서 이용할 수 있다.

(http://www.postgresql.org/awbook.html) 여기에는 각각의 인터페이스에서 이용가능한 접속, 질의 그리고

결과 조회 함수들에 대해서 설명해 두었다.

 

Bruce Momjian

2001-09-14

 

============================================================

다음은 원본 내용입니다.

============================================================

 

Finer Details

 

This section describes each step in more detail.

 

. Connection

. Query

. Result

 

 

Connection

 

You will notice a string is used to specify the database in the connection function call. Connection parameters include:

 

 

host

hostaddr (host address)

port

dbname

user

password

There are other options available too. The connection string format is option=value option=value ....

For example, host=billing.bigco.com dbname=finance user=sam connects as user sam

to database finance on host billing.bigco.com. The connection handle returned should be checked

to make sure it succeeded before sending a query.

 

 

Query

 

You will notice queries are passed to the database as ordinary strings. This makes programming very

easy. You can easily create queries by creating query strings:

 

        char query_string[500];  
        char name[50];  
        int unique_id;  


        sprintf(query_string, "SELECT * FROM tab WHERE col = %d", unique_id); 
        res = PQexec(conn, query_string);   

or 

  

        sprintf(query_string, "INSERT INTO tab VALUES (%d, '%s')", unique_id, name); 
        res = PQexec(conn, query_string);   

 


You can see more examples in the programs in the previous section.

 

The result handle should be checked to make sure the query succeeded before continuing

to access the result. In the last query, name is a character string variable. If it contains

single quotes, you have to convert them to backslash-quote (') or two single-quotes ('').

If name contains backslashes, you have to convert them to double backslashes (\).

 

 

Result

 

Accessing result information is straightforward. First, only SELECT returns a result set.

Other commands like INSERT and DELETE return simple status information.

 

SELECT's result set is a table made up of rows and columns. Of course, sometimes the result

is only one row or one column, but it still needs to be accessed as a table. This accesses the first

column in the first row of the result:

 

        printf("%s\n", PQgetvalue(res, 0, 0));   

 

The first row and first column are numbered zero. In libpq, PQntuples() returns the number of rows

in the result, and PQnfields() returns the number of columns. Using this information, any result

value can be retrieved by specifying its row and column. Here is a more complicated example that

displays all values returned in a result.

 

         
        int i, j;  
          
        for (i = 0; i < PQntuples(res); i++)                /* loop through all rows returned */ 
            for (j = 0; j < PQnfields(res); j++)                /* loop through all columns 
                printf("%s\n", PQgetvalue(res, i, j));          /* print the value returned */ 

 

Unless a binary cursor is used, all values are returned as ASCII strings. If you need them

in a different format for your application, the values must be converted in the application. POSTGRESQL

interfaces have many more functions that return useful information:

 

o Result status
  . error messages strings associated with connection and result handles 

o SELECT result information 
  . number of rows returned 
  . number of columns returned 
  . column names associated with result column numbers 
  . column numbers associated with result column names 
  . column data types 
  . column data type modifiers 
  . column length 
  . cursor binary status 

o SELECT values 
 . value null status 
 . value length 

o Non-SELECT result information 
  . command status strings 
  . OID of inserted rows

 

 

Conclusion

 

This article illustrates the steps needed use POSTGRESQL in applications:

 

Issue a connection request and get a connection handle

Issue a query and get a result handle

Access the result

 

This article focuses on writing applications using only two programming languages.

However, writing applications in other languages uses the same concepts. A chapter

showing the same application written in various programming languages can be found

in my book, PostgreSQL: Introduction and Concepts at

http://www.postgresql.org/docs/awbook.html. More information about each programming interface is

available in the PostgreSQL Programmer's Manual, http://www.postgresql.org/docs/programmer/programmer.html.

It covers the connection, query, and result functions specific to each interface.

 

Bruce Momjian

2001-09-14

[Top]
No.
제목
작성자
작성일
조회
42301차원 정수형 배열 조작 함수들 [1]
김상기
2002-06-17
12950
4223PL/pgsql로 구현한 fulltext index
김상기
2002-06-11
13971
4165plpython 이용하기 + full text index
김상기
2002-04-25
12156
3544PostgreSQL 응용 프로그램 작성하기 (V)
정재익
2001-10-18
13096
3537PostgreSQL 응용 프로그램 작성하기 (IV)
정재익
2001-10-18
11844
3536PostgreSQL 응용프로그램 작성하기 (III)
정재익
2001-10-18
11004
3522PostgreSQL 응용 프로그램 작성하기 (II)
정재익
2001-10-17
11234
Valid XHTML 1.0!
All about the DATABASE... Copyleft 1999-2023 DSN, All rights reserved.
작업시간: 0.051초, 이곳 서비스는
	PostgreSQL v16.1로 자료를 관리합니다