본문 바로가기
Develop/Java

JDBC 프로그래밍

by jaekk 2018. 7. 14.

jdbc 프로그래밍


자바에서 데이터베이스의 데이터를 다루는 프로그래밍


1. 드라이버 로드

    선행작업: DBMS사에서 제공하는 드라이버 등록 

     - 홈페이지 다운

     - DBMS설치 폴더

       C:\app\doosa\product\11.2.0\dbhome_1\jdbc\lib\ojdbc6.jar

    

     Class.forName("oracle.jdbc.driver.OracleDriver");



2. 데이터 베이스 연결

Connection conn = DriverManager.getConnection(jdbcUrl, id, pw);

-jdbcUrl: 오라클 접속 정보

-id : 오라클 접속 계정

-pw: 접속 계정 비밀번호


3. 쿼리 실행

[select]

- CreateStatement stmt = conn.CreateStatement();

  stmt.executeQuery();

- PrepareStatement pstmt = conn.PrepareStatement(sql);

  pstmt.setString(index, value)

  pstmt.executeQuery();


[update, insert, delete]

- CreateStatement stmt = conn.CreateStatement();

  int rtnRow  = stmt.executeUpdate();

- PrepareStatement pstmt = conn.PrepareStatement(sql);

  pstmt.setString(index, value)

  int rtnRow = pstmt.executeUpdate();

-return값으로 성공한 행의 개수를 반환

  쿼리 정상 실행여부 따질 수 있다.


4. 데이터 베이스 종료

     conn.close();

     - 메모리 낭비를 제한하기 위해 연결 종료



    


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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class JDBCOracleExample2 {
 
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        PreparedStatement pstmt = null;
        int retrnRow = 0;
 
        String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:orcl";
        String id = "SCOTT";
        String pw = "1234";
 
        // 4. 요청할 sql문- select문
        int empno = 7935;
        int mgr = 7369;
        String seleSql1 = "select * from emp order by empno";
        String seleSql2 = "select * from emp where empno = ?";
        String inserSql = "insert into emp values (?,?,?,?,?,?,?,?)";
        String updaSql = "update emp set mgr = ? where empno = ?";
        String deleSql = "delete emp where empno =?";
        
 
        try {
            // 1. 데이터베이스의 드라이버 로드
            Class.forName("oracle.jdbc.driver.OracleDriver");
 
            // 2. 데이터베이스 연결
            conn = DriverManager.getConnection(jdbcUrl, id, pw);
 
            System.out.println("Oracle 데이터 베이스에 연결되었습니다.");
            System.out.println("--------------------------------------------");
 
            stmt = conn.createStatement();
            rs = stmt.executeQuery(seleSql1);
 
            System.out.println("[직원리스트]");
            while (rs.next()) {
                System.out.println("-------------------------");
                System.out.println("사원번호: " + rs.getInt(1));
                System.out.println("사원명: " + rs.getString(2));
                System.out.println("직업 :" + rs.getString(3));
                System.out.println("상사명 :" + rs.getInt(4));
                System.out.println("입사일 :" + rs.getString(5));
                System.out.println("급여 :" + rs.getInt(6));
                System.out.println("커미션 :" + rs.getInt(7));
                System.out.println("부서번호 :" + rs.getString(8));
            }
 
            System.out.println("-------------------------");
 
            // #####################[  insert  ]##################
            System.out.println("[직원정보 추가하기]");
            String sql2 = "insert into emp values (?,?,?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql2);
 
            pstmt.setInt(17935);
            pstmt.setString(2"MINJEONG");
            pstmt.setString(3"STUDENT");
            pstmt.setInt(47934);
            pstmt.setString(5"18/07/13");
            pstmt.setInt(6700);
            pstmt.setInt(7100);
            pstmt.setInt(840);
 
            pstmt.executeUpdate();
 
            // ####################[  추가된 사원 정보 출력하기  ] #########################
            pstmt = conn.prepareStatement(seleSql2);
            pstmt.setInt(1, empno);
            // select의 결과를 resultSet 객체에 담는다.
 
            rs = pstmt.executeQuery();
 
            System.out.println("[추가된 직원 정보 출력하기]");
 
            while (rs.next()) {
                System.out.println("-------------------------");
                System.out.println("사원번호: " + rs.getInt(1));
                System.out.println("사원명: " + rs.getString(2));
                System.out.println("직업 :" + rs.getString(3));
                System.out.println("상사명 :" + rs.getInt(4));
                System.out.println("입사일 :" + rs.getString(5));
                System.out.println("급여 :" + rs.getInt(6));
                System.out.println("커미션 :" + rs.getInt(7));
                System.out.println("부서번호 :" + rs.getString(8));
            }
            System.out.println("-------------------------");
            
            
//            ###############[  사원 정보 수정하기  ]##################
            System.out.println("[사원 정보 수정하기]");
            System.out.println("-------------------------");
            pstmt = conn.prepareStatement(updaSql);
            pstmt.setInt(1,mgr);
            pstmt.setInt(2, empno);
            retrnRow = pstmt.executeUpdate();
            
            if(retrnRow != 0){
                System.out.println("업데이트가 성공하였습니다.");
            }
            
            pstmt = conn.prepareStatement(seleSql2);
            pstmt.setInt(1, empno);
            rs = pstmt.executeQuery();
            
            System.out.println("[수정된 사원 정보 출력하기]");
            
            while(rs.next()){
                System.out.println("-------------------------");
                System.out.println("사원번호: " + rs.getInt(1));
                System.out.println("사원명: " + rs.getString(2));
                System.out.println("직업 :" + rs.getString(3));
                System.out.println("상사명 :" + rs.getInt(4));
                System.out.println("입사일 :" + rs.getString(5));
                System.out.println("급여 :" + rs.getInt(6));
                System.out.println("커미션 :" + rs.getInt(7));
                System.out.println("부서번호 :" + rs.getString(8));
            }
            System.out.println("-------------------------");
            
            
//            ###############[  사원 정보 삭제하기  ]##################
            System.out.println("[사원 정보 삭제하기]");
            System.out.println("-------------------------");
            
            pstmt = conn.prepareStatement(deleSql);
            pstmt.setInt(1, empno);
            
            retrnRow = pstmt.executeUpdate();
            
            if(retrnRow == 1){
                System.out.println("해당 회원의 정보가 삭제되었습니다.");
            }
            
            
            // 3. 데이터 베이스의 연결 종료
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
 
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("데이터베이스 드라이버를 찾을 수 없습니다.");
            e.printStackTrace();
        }
 
    }
 
}
 
c
s


'Develop > Java' 카테고리의 다른 글

[설정]Navigator설정  (1) 2018.08.11
Source not found  (0) 2018.07.16
Singleton 싱글톤처리  (0) 2018.07.09
제네릭_생활코딩  (0) 2018.05.07
stack 구현하기  (0) 2018.05.06

댓글