JDBC 오라클 데이터베이스 연동하기


먼저 오라클 데이터베이스 설치하여 emp 테이블을 생성한 전제로 진행한다. (다운로드 - www.oracle.com)
오라클 드라이버를 클래스 패스에 설정해야 자바 애플리케이션과 오라클 데이터베이스를 연동할 수 있다.
[Windows]-[Preferences]-[Java]-[Build Path]-[ClassPath Variables]에 있는 JRE_LIB 경로를 파악하여
lib\ext 디렉토리에 오라클 설치경로(C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib)에 있는'ojdbc6_g.jar'
파일을 복사하면 자동으로 드라이버가 클래스 패스에 추가된다.

* Select 쿼리 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@WebServlet("/select")
public class SelectServlet extends HttpServlet {
 
    private static final long serialVersionUID = -2214077158028938610L;
 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        String driver = "oracle.jdbc.OracleDriver"// 오라클 드라이버 클래스 파일명
        String url = "jdbc:oracle:thin:@localhost:1521:XE"// 오라클 위치,포트번호,DB정보
        String id = "root"// 오라클 접속 계정
        String password = "1234"// 오라클 접속 비밀번호
 
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        String result = null;
        
        try {
            Class.forName(driver); // 드라이버 로딩
            con = DriverManager.getConnection(url, id, password); // DB 커넥션 맺기
 
            String sql = "select eid, ename, salary from emp";
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
 
            while (rs.next()) {
                String eid = rs.getString("eid");
                String ename = rs.getString("ename");
                int salary = rs.getInt("salary");
                result  = eid + " " + ename + " " + salary;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { // 자원 반납
                if (rs != null)
                    rs.close();
                if (stmt != null)
                    stmt.close();
                if (con != null)
                    con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
        request.setAttribute(result, result);
        response.setCharacterEncoding("UTF-8");
        request.getRequestDispatcher("/select.jsp").forward(request, response);
    }
 
}
cs
Select 쿼리 요청에는 executeQuery 메소드를 사용하여 테이블 형태인 ResultSet 객체를 얻는다.
ResultSet 객체는 포인터를 이용해서 원하는 데이터를 얻을 수 있기 때문에 먼저 포인터를 이용해서 레코드를 선택하고 포인터가 가리키는 레코드의 컬럼을 지정해서 데이터를 얻는다. 레코드를 선택하는 메소드는 next()를 사용하고 컬럼은 데이터형에 맞는 get*(컬럼명)메소드를 사용한다.

파일 및 데이터베이스는 외부 자원이기 때문에 사용한 후에는 반드시 자원을 해제시켜야 된다. 해제시킬 때에는 사용한 역순으로 해제시킨다.
예외 발생 여부에 관계없이 항상 자원을 반납해야하므로 finally 문에 코드를 구현하도록 한다.

* Update 쿼리 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
 
    private static final long serialVersionUID = -2214077158028938610L;
 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        request.setCharacterEncoding("UTF-8");
        String eid = request.getParameter("eid");
        String ename = request.getParameter("ename");
        int salary = Integer.parseInt(request.getParameter("salary"));
        
        String driver = "oracle.jdbc.OracleDriver";
        String url = "jdbc:oracle:thin:@localhost:1521:XE";
        String id = "root";
        String password = "1234";
        
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, id, password);
        
            String sql = "update emp set ename = ?, salary = ? where eid = ?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, ename);
            pstmt.setInt(2, salary);
            pstmt.setString(3, eid);
            
            int count = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (pstmt != null)
                    pstmt.close();
                if (con != null)
                    con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        response.setCharacterEncoding("UTF-8");
        response.sendRedirect("/select?eid=" + eid);
    }
    
}
cs
PrepareStatement 객체를 이용하면 SQL 문을 먼저 작성하고 나중에 필요한 데이터를 설정할 수 있다.
set 메소드를 이용해 인덱스에 값을 지정한다. 인덱스는 작성한 SQL 문에 있는 '?' 심벌의 순서를 의미한다. 
'?' 심벌 수와 set 메소드 수는 같아야 한다.

DML(Insert, Update, Delete) 쿼리 요청에는 executeUpdate 메소드를 사용하여 데이터를 처리하고 변경된 레코드의 개수를 얻는다.


+ Recent posts