Java - DAO

2020. 6. 29. 22:54Java

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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
 
public class CustomerDAO {
    /*
     * DAO(Data Access Object)데이터 접근 객체
     * - 데이터베이스와 연동하여 작업을 처리하는 객체
     * - DTO 객체를 사용하여 저장된 데이터를 DB에 전달하여 추가하거나,
     * - DB로부터 전달받은 데이터를 외부로 전달하는 역할
     * - 각 기능별로 메서드를 구분하여 정의
     */
    
    
    //DTO 객체를 전달받아 DB에 INSERT 작업을 수행할 메서드 insert() 정의
 
    public int insert(CustomerDTO dto) {
        System.out.println("CustomerDAO - insert()");
        int insertCount=0;
        
        //DTO객체에 저장되어 있는 데이터 출력
        
//        System.out.println(dto.getIdx()+", "+dto.getId()+", "+dto.getPassword()+", "+dto.getName()+", "+dto.getJumin());
        
        //DB Insert 작업 수행
        Connection con=null;
        PreparedStatement pstmt=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/java5";
            String user="root";
            String pass="1234";
            
            con=DriverManager.getConnection(url,user,pass);
            String sql="INSERT INTO customer VALUES(null,?,?,?,?)";
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1, dto.getName());
            pstmt.setString(2, dto.getId());
            pstmt.setString(3, dto.getPassword());
            pstmt.setString(4, dto.getJumin());
            
            insertCount=pstmt.executeUpdate();
            return insertCount;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        
        return insertCount;//INSERT 실행 구문을 리턴
    }
 
    public int update(String id, String oldPassword, String newPassword) {
        int updateCount=0;
        System.out.println(id+", "+oldPassword+", "+newPassword);
        
        Connection con=null;
        PreparedStatement pstmt=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/java5";
            String user="root";
            String pass="1234";
            
            con=DriverManager.getConnection(url,user,pass);
            //id와 password(oldPassword)가 일치하는 레코드를 찾아
            //password를 newPassword 값으로 변경
            String sql="UPDATE customer SET password=? where id=? && password=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1, newPassword);
            pstmt.setString(2, id);
            pstmt.setString(3, oldPassword);
            
            
            updateCount=pstmt.executeUpdate();
            return updateCount;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        return updateCount;
    }
 
    public int delete(CustomerDTO dto) {
        int deleteCount=0;
        Connection con=null;
        PreparedStatement pstmt=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/java5";
            String user="root";
            String pass="1234";
            
            con=DriverManager.getConnection(url,user,pass);
            String sql="DELETE FROM customer where id=? && password=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1, dto.getId());
            pstmt.setString(2, dto.getPassword());
            
            
            deleteCount=pstmt.executeUpdate();
            return deleteCount;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        return deleteCount;
    }
    
    //목록을 조회
//    public ArrayList select() {
//        Connection con=null;
//        PreparedStatement pstmt=null;
//        ResultSet rs=null;
//        
//        ArrayList list=null;//여러개의 dto 객체를 저장하여 리턴할 때 사용할 변수
//        
//        String url="jdbc:mysql://localhost:3306/java5";
//        String user="root";
//        String pass="1234";
//        try {
//            Class.forName("com.mysql.jdbc.Driver");
//            
//            
//        
//        con=DriverManager.getConnection(url,user,pass);
//        
//        String sql="SELECT * FROM customer";
//        pstmt=con.prepareStatement(sql);
//        
//        rs=pstmt.executeQuery();
//        
//        //여러개의 DTO 객체를 저장하기 위한 ArrayList 객체 생성
//        list=new ArrayList();
//        
//        while(rs.next()) {
////            System.out.println(rs.getInt("idx"));
////            System.out.println(rs.getString("name"));
////            System.out.println(rs.getString("id"));
////            System.out.println(rs.getString("password"));
////            System.out.println(rs.getString("jumin"));
//            
//            //1개의 레코드(한 명의 데이터)를 CustomerDTO 객체에 저장
//            //비즈니스 로직!!!!!!
//            
//            CustomerDTO dto=new CustomerDTO();
//            dto.setIdx(rs.getInt("idx"));
//            dto.setName(rs.getString("name"));
//            dto.setId(rs.getString("id"));
//            dto.setPassword(rs.getString("password"));
//            dto.setJumin(rs.getString("jumin"));
//            
//            //전체 레코드를 저장하는 ArrayList 객체에 DTO 객체 저장
//            
//            list.add(dto);            
//            
//        }
//            
//        
//        } catch (ClassNotFoundException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (SQLException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } finally {
//        try {
//            rs.close();
//            pstmt.close();
//            con.close();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//            
//        }
//        
//        
//        
//        
//        return list;
//    }
    
    public ArrayList select() {
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        ArrayList list=null;
        
        //1단계, 2단계를 수행하는 getConnection() 메서드를 호출하여 Connection 객체 리턴받기
        Connection con=getConnection();
        
        
        //3단계, 4단계
        try {
            String sql="SELECT * FROM customer";
            pstmt=con.prepareStatement(sql);
            
            rs=pstmt.executeQuery();
            
            //여러개의 DTO 객체를 저장하기 위한 ArrayList 객체 생성
            list=new ArrayList();
            
            while(rs.next()) {
//            System.out.println(rs.getInt("idx"));
//            System.out.println(rs.getString("name"));
//            System.out.println(rs.getString("id"));
//            System.out.println(rs.getString("password"));
//            System.out.println(rs.getString("jumin"));
                
                //1개의 레코드(한 명의 데이터)를 CustomerDTO 객체에 저장
                //비즈니스 로직!!!!!!
                
                CustomerDTO dto=new CustomerDTO();
                dto.setIdx(rs.getInt("idx"));
                dto.setName(rs.getString("name"));
                dto.setId(rs.getString("id"));
                dto.setPassword(rs.getString("password"));
                dto.setJumin(rs.getString("jumin"));
                
                //전체 레코드를 저장하는 ArrayList 객체에 DTO 객체 저장
                
                list.add(dto);            
                
            }
        } catch (SQLException e) {
            System.out.println("SQL 구문 오류 발생!@!#$@!#");
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                pstmt.close();
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        
        return list;
    }
    
    //1단계와 2단계 작업을 통해 Connection 객체를 리턴하는 메서드
    public Connection getConnection() {
        String driver="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/java5";
        String user="root";
        String pass="1234";
        Connection con=null;
        try {
            Class.forName(driver);
            con=DriverManager.getConnection(url,user,pass);
        } catch (ClassNotFoundException e) {
            System.out.println("드라이버 연결실패");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("DB 연결실패");
            e.printStackTrace();
        }
        return con;
    }
    
    
    
}
 
 
 
 
cs

 

DAO는 앞서 봤던  DTO와 다르게 DB 연결 작업 문장들을 작성해야 하고 삽입, 삭제, 갱신, 조회 등 여러 작업을 위한 메서드를 미리 만들어 두는 곳이다. SQL 구문까지 따로 사용해야 할 작업에 따라 각자 다 선언해 두고

표현할 곳으로 넘어가 간단하게 객체 생성 후 메서드만 불러오면 끝이 나게 해 둔다. SELECT 작업을 보면

ArrayList를 선언하여 DB의 데이터들을 리스트로 전달받아 작업을 할 수 있게 해 두었다.

메서드들이 확실히 작동을 하는지 확인을 하기 위하여 리턴 값을 활용한 int형 변수 선언 후 작업의 실행문을 변수에 삽입하면 if문을 사용하여 작업이 제대로 실행되었는지 확인이 가능하고 이게 유지보수 면에서 훨씬 수월하기 때문에

따로 선언해 두었다. 간단하게  SELECT, INSERT, DELETE, UPDATE구문만 해보았다.

그리고 마지막에 보면 항상 중복이 되는 1단계와 2단계를 따로 메서드로 빼놓고 Connection 타입으로 리턴 타입을 정해 놓고 작업을 또다시 모듈화를 시켜 보았다.

확실히 많은 문장들의 중복이 제거 되었고 너무 편하게 작업할 수 있었다.

'Java' 카테고리의 다른 글

Java - Wrapper  (0) 2020.06.30
Java - DAO,DTO활용  (0) 2020.06.29
Java - DTO  (0) 2020.06.29
Java - JDBC-2  (0) 2020.06.29
Java - JDBC  (0) 2020.06.29