자바 데이터베이스

자바 데이터베이스


JDBC 기본 프로그래밍


JDBC사용법
1 . 데이터베이스와 연결하는 프로그램 파일을 찾아 인스턴스를 생성(API 검색)
2 . 연결을 관리하는 Connection 객체생성
3 . 작업을 처리할 Statement, PreparedStatement, CallableStatement객체 생성
4 . ResultSet 객체를 통한 Query 결과 처리
5 . 접속종료

  • 1단계 작업은 데이터베이스와 연결하여 사용할 파일들이 있는지를 확인하는 단계이다
    여기서 굳이 인스턴스를 발생시키지 않더라도 드라이버 존재 유무만 확인하면 프로그램 실행에는 지장이없다

ex )

1
2
3
4
5
6
try{
Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("Driver load ok ....");
}catch(ClassNotFoundException ee){
System.err.println("Driver load ng......");
}

2단계 작업은 찾은 드라이버 클래스를 통해 우리가 설치한 데이터베이스 서버와
연결하는 Connection 객체를 생성하는 단계. Connection 객체는 DriverManager라는 클래스의
getConnection()이라는 static 메서드로 생성한다. 예외는 SQLException처리
ex )

1
2
3
4
5
6
7
8
9
String url = "jdbc:mysql://localhost:3306/java";
String id = "root";
String pass = "1234";
try{
Connection conn = DriverManager.getConnection(url, id, pass);
System.out.println("Connection ok ....");
}catch(SQLException ee){
System.err.println("Connection ng ....");
}

3단계 작업은 연결된 포트를 통해 Query문을 보낼수 있도록 도와주는 객체를 생성하는 작업이다
자바에서는 크게 세 가지 방법으로 Query문을 처리할 수 있는데 , 첫 번째는 정적 Query를
처리할때 유리하도록 만들어둔 객체인 Statement 객체의 생성이고 , 두번째는 동적 Query를 처리할때
유리하도록 만들어둔 객체인 PreparedStatement객체이다 . 마지막 객체는 프로시저를 호출할수 있도록
도와주는 객체가 있다
ex )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Statement를 처리하는 예제
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select * from tables");
stmt.executeUpdate("insert into tables values (data1, data2 ....)");
}catch(SQLException ee){
System.err.println("error = " + ee.toString());
}

//PreparedStatement를 처리하는 예제
try{
PreparedStatement pstmt = conn.preparedStatement("select * from tables");
pstmt.setInt(1, 10);
PreparedStatement pstmt1 = conn.preparedStatement("insert into tables values (?, ?, ?");
pstmt1.setInt(1, 10);
pstmt1.setString(2 , "shim");
pstmt1.setString(3 , "seob");
ResultSet rs = pstmt.executeQuery();
pstmt1.executeUpdate();
}catch(SQLException ee){
System.err.println("error = " + ee.toString());
}

  • 4단계 작업은 execute메서드 중 실행 결과를 가져오는 executeQuery에 대한 내용이다 .
    앞서 executeQuery()메서드를 통해 결과를 얻게되면 그것은 고스란히 ResultSet객체의 관리로 남게 된다
    물론 ResultSet객체가 Vector처럼 Query의 결과물을 모두 담고 있다는 이야기는 아니다
    단지 데이터베이스를 통해 획득한 결과를 관리만 할 뿐이다 .
    ex )

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    try{
    ResultSet rs = pstmt.executeQuery();
    while(rs.next()){
    int a = rs.getInt(1);
    String b = rs.getString(2);
    String c = rs.getString(3);
    System.out.println(a + " , " + b + " , " + c );
    }
    }catch(SQLException ee){
    System.err.println("errer = " + ee.toString());
    }
  • 5단계작업은 지금까지 데이터베이스와 연결하려고 열어둔 동로를 모두 닫는 작업이다 .
    ex )

    1
    2
    3
    4
    5
    6
    7
    8
    9
    try{
    rs.close();
    stmt.close();
    pstmt.close();
    pstmt1.close();
    conn.close();
    }catch(SQLException ee){
    System.err.println("errer = " + ee.toString());
    }
Share