BackEnd/Java

Java :: JDBC DAO 소스

초록 (green) 2016. 4. 26. 23:39

Servlet + jstl + JDBC 를 이용한 게시판 소스 중 JDBC DAO 파일 소스 전문 JDBC를 공부하다가, 

Mybatis로 발전해서 게시판 프로젝트 공부를 했었는데

다시 JDBC를 이용하여 혼자 힘으로 해보려니 조금 어려운 면이 있기도 했다.

 

확실히 Mybatis가 편하다.

 

 

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
package com.dao;
 
import java.sql.*;
import java.util.*;
 
import com.vo.Person;
 
public class PersonDAO implements PersonDAOImpl {
 
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    
    String url = "jdbc:mysql://localhost:3306/basicjsp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
    String id = "jspid";
    String pass = "jsppass";
    
    String sql = "";
        
    public void connectDB() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            
            conn = DriverManager.getConnection(url, id, pass);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public List<HashMap<String, Object>> selectAll() {
        List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
    
        try {
            
            sql = "SELECT id, name, sex, age, DATE_FORMAT(date, '%Y-%m-%d') AS date, rcount FROM persons";
            
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {    
                connectDB();
                
                HashMap<String, Object> params = new HashMap<String, Object>();
                
                params.put("id", rs.getInt("id"));
                params.put("name", rs.getString("name"));
                params.put("sex", rs.getString("sex"));
                params.put("age", rs.getInt("age"));
                params.put("date", rs.getShort("date"));
                params.put("rcount", rs.getInt("rcount"));
                
                params.put("column""id");
                params.put("sort""ASC");
                
                list.add(params);
            }
            
            conn.close();
            pstmt.close();
            rs.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        
        return list;
    }
 
    @Override
    public List<HashMap<String, Object>> selectAllLimit(int offset, int recordsPerPage,
            String sortItem, String sortMethod) {
        List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
         
        try {
            connectDB();
            
            sql = "SELECT id, name, sex, age, DATE_FORMAT(date, '%Y-%m-%d') AS date, rcount FROM persons ";
            
            if (sortItem != null && sortItem.equals("id")) {
                sql += "ORDER BY id ";
            }
            else if (sortItem != null && sortItem.equals("name")) {
                sql += "ORDER BY name ";
            }
            else
                sql += "ORDER BY age ";
            
            if (sortMethod != null && sortMethod.equals("ASC")) {
                sql += "ASC ";
            }
            else {
                sql += "DESC ";
            }
            
            sql += "LIMIT " + offset + ", " + recordsPerPage;
            
            pstmt = conn.prepareStatement(sql);
 
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                HashMap<String, Object> params = new HashMap<String, Object>();
                
                params.put("id", rs.getInt("id"));
                params.put("name", rs.getString("name"));
                params.put("sex", rs.getString("sex"));
                params.put("age", rs.getInt("age"));
                params.put("date", rs.getString("date"));
                params.put("rcount", rs.getInt("rcount"));
                
                params.put("offset", offset);
                params.put("recordsPerPage", recordsPerPage);
                params.put("sortItem", sortItem);
                params.put("sortMethod", sortMethod);
                
                list.add(params);
            }
            
            conn.close();
            pstmt.close();
            rs.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        
        return list;
    } 
    
    @Override
    public Person selectById(int id) {
        Person person = new Person();
        
        try {
            connectDB();
            
            sql = "SELECT * FROM persons WHERE id = ?";
            
            pstmt = conn.prepareStatement(sql);
            
            pstmt.setLong(1, id);
            
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                person.setId(rs.getInt(1));
                person.setName(rs.getString(2));
                person.setSex(rs.getString(3));
                person.setAge(rs.getInt(4));
                person.setDate(rs.getString(5));
                person.setrCount(rs.getInt(6));
            }
            
            conn.close();
            pstmt.close();
            rs.close();
            
        } catch (Exception e) { }
        
        return person;
    }
 
    @Override
    public int selectCount() {
        int n = 0;
        
        try {
            connectDB();
            
            String sql = "SELECT COUNT(*) FROM persons";
            
            pstmt = conn.prepareStatement(sql);
            
            rs = pstmt.executeQuery();
            
            rs.next();
            
            n = rs.getInt(1);
            
            pstmt.close();
            rs.close();
            
        } catch (Exception e) { }
        
        return n;
    }
 
    @Override
    public int insert(Person person) {
        int id = -1;
        
        sql = "INSERT INTO persons (name, sex, age, rcount) VALUES (?, ?, ?, 0)";
        
        try {
            connectDB();
            
            pstmt = conn.prepareStatement(sql);
            
            pstmt.setString(1, person.getName());
            pstmt.setString(2, person.getSex());
            pstmt.setInt(3, person.getAge());
            
            pstmt.executeUpdate();
            
            pstmt.close();
            conn.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        
        return id;
    }
 
    @Override
    public void update(Person person) {    
        sql = "UPDATE persons SET name = ? , sex = ?, age = ? WHERE id = ?";
        
        try {
            connectDB();
            
            pstmt = conn.prepareStatement(sql);
            
            pstmt.setString(1, person.getName());
            pstmt.setString(2, person.getSex());
            pstmt.setInt(3, person.getAge());
            pstmt.setInt(4, person.getId());
            
            pstmt.executeUpdate();
            
            pstmt.close();
            conn.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void updateCount(int id) {    
        sql = "UPDATE persons SET rcount = rcount + 1 WHERE id = ?";
        
        try {
            connectDB();
            
            pstmt = conn.prepareStatement(sql);
            
            pstmt.setInt(1, id);
            
            pstmt.executeUpdate();
            
            pstmt.close();
            conn.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void delete(int id) {
        sql = "DELETE FROM persons WHERE id = ?";
        
        try {
            connectDB();
            
            pstmt = conn.prepareStatement(sql);
            
            pstmt.setInt(1, id);
            
            pstmt.executeUpdate();
            
            pstmt.close();
            conn.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }    
    }
}
cs

 

 

- selectAll : 리스트 전체 출력 메소드

- selectAllLimit : 정렬 방식에 따라 변경되는 리스트 출력 메소드

if문과 LIMIT 를 이용한 쿼리를 구현하는데에서 시행착오가 조금 있었다.

- selectById : 특정 게시글을 선택했을 때 해당 글 하나의 정보만을 출력하는 메소드

- selectCount : 전체 리스트 수를 출력하는 메소드

- insert : 게시글 삽입 메소드

- update : 게시글 수정 메소드

- updateCount : 게시글 조회수 증가 메소드

- delete : 게시글 삭제 메소드