POSTGRES  DBMS + JDBC


데이타 베이스 만들기


% createdb mydb
% psql mydb
Welcome to the POSTGRESQL interactive sql monitor:
  Please read the file COPYRIGHT for copyright terms of POSTGRESQL

   type \? for help on slash commands
   type \q to quit
   type \g or terminate with semicolon to execute query
You are currently connected to the database: mydb

mydb=> create table weather (city varchar(80), temp_lo int, temp_hi int, date date);
CREATE
mydb=> insert into weather values('seoul', 26, 32, '8/17/1997')
mydb-> \g
INSERT 21059
mydb=> insert into weather values('pusan', 27, 34, '8/17/1997')
mydb-> \g
INSERT 21060
mydb=> select * from weather ;
city |temp_lo|temp_hi|      date
-----+-------+-------+----------
seoul|     26|     32|08-17-0000
pusan|     27|     34|08-17-0000
(2 rows)

mydb=> select * from weather where city='seoul';
city |temp_lo|temp_hi|      date
-----+-------+-------+----------
seoul|     26|     32|08-17-0000
(1 row)

mydb=> select city from weather where temp_hi > 30 ;
city 
-----
seoul
pusan
(2 rows)

mydb=> select city, temp_hi from weather where temp_hi > 30 ;
city |temp_hi
-----+-------
seoul|     32
pusan|     34
(2 rows)

mydb=> \q


JDBC 이용해서 데이타베이스 접근하기


Postgres DBMS용 JDBC 드라이버를 /usr/local/java/JavaPostgres95-0.4 디렉토리에
설치한다. JDBC 드라이버는 http://www.postgresql.org/에서 구할 수 있다.
JDBC 드라이버를 설치한 다음에  자신의 CLASSPATH 환경변수를 변경해주어야 한다.
C-Shell 사용자는 다음 내용을 $HOME/.cshrc 파일에 추가한다.

setenv  CLASSPATH  /usr/local/java/JavaPostgres95-0.4:$CLASSPATH

추가한 후에
% source $HOME/.cshrc

Bourne-Shell 과 Korn-Shell 사용자는 다음 내용을 $HOME/.profile 파일에 추가한다.

CLASSPATH=/usr/local/java/JavaPostgres95-0.4:$CLASSPATH
export  $CLASSPATH

추가한 후에
# .  $HOME/.profile


% vi  JdbcTest.java

     1  import java.sql.*;
     2
     3  public class JdbcTest {
     4     public static void main(String argv[]) {
     5        try {
     6  //         DriverManager.setLogStream(System.out);
     7
     8           Driver pgd = (Driver) new postgres95.PGDriver();
     9
    10           String url = "jdbc:postgres95:mydb";
    11
    12           Connection conn = DriverManager.getConnection(url,"","");
    13
    14           Statement stat = conn.createStatement();
    15
    16           ResultSet rs = stat.executeQuery("Select * from weather");
    17
    18           while ( rs.next() ) {
    19              String city = rs.getString(1);
    20              short lo = rs.getShort(2);
    21              short hi = rs.getShort(3);
    22              Date date = rs.getDate(5);
    23              System.out.println(city+" "+lo+" "+hi+" "+date);
    24           }
    25           stat.close();
    26           conn.close();
    27        } catch ( Exception e ) {
    28        }
    29     }
    30  }


% javac JdbcTest.java

% java  JdbcTest


간단한 설명


JDBC 프로그래밍 절차
1. 각 데이타베이스에 맞는 JDBC 드라이버를 메모리에 로드한다.

   8           Driver pgd = (Driver) new postgres95.PGDriver();


2. DriverManager의 getConnection() 메소드를 이용해서 데이타베이스에
   연결한다.  getConnection() 메소드는 Connection 을 리턴한다.

   12           Connection conn = DriverManager.getConnection(url,"","");


3. Connection의 createStatement() 메소드를 이용해서 Statement 를 만다느다.

   14           Statement stat = conn.createStatement();


4. Statement의 executeQuery() 메소드를 이용해서 SQL 문장을 데이타베이스에
   전달한다. executeQuery() 메소드는 ResultSet을 리턴한다. ResultSet은
   테이블 형태로 되어있다.

   16           ResultSet rs = stat.executeQuery("Select * from weather");


5. ResultSet은 테이블 형태로 되어있기 때문에 cursor를 이동하면서 결과를
   검색한다. next() 메소드는 cursor를 한 행씩 이동 시킨다. cursor가
   위치한 행에서 각 필드의 값을 검색하기 위해서는 getXXX()함수를 이용한다.
   주의할 점은 값을 한번 읽으면, 다시 접근할 수 없다는 사실이다.

   18           while ( rs.next() ) {
   19              String city = rs.getString(1);
   20              short lo = rs.getShort(2);
   21              short hi = rs.getShort(3);
   22              Date date = rs.getDate(5);
   23              System.out.println(city+" "+lo+" "+hi+" "+date);
   24           }


6. 작업이 끝난 경우에는 Statement와 Connection 에서 close() 메소드를
   호출해주어야 한다.

   25           stat.close();
   26           conn.close();

자바추천학원:
http://www.it-bank.or.kr/prom/java_main.htm
Posted by 김윤석

카테고리

놀며즐기고 공부하기 (685)
 IT 정보 (653)
 재테크 (0)
 엔터테이먼트 (11)
 인터넷마케팅 (0)
 사이트 추천 (1)
사이드바 열기