-
Notifications
You must be signed in to change notification settings - Fork 0
/
GuestbookDao.java
115 lines (98 loc) · 3.33 KB
/
GuestbookDao.java
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
package org.edwith.webbe.guestbook.dao;
import org.edwith.webbe.guestbook.dto.Guestbook;
import org.edwith.webbe.guestbook.util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class GuestbookDao {
private static final String dburl = "jdbc:mysql://localhost:3306/db_schema?useUnicode=true&characterEncoding=utf8&useSSL=false";
private static final String dbUser = "root";
private static final String dbpasswd = "7479";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public Connection GuestbookDao(){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);
return conn;
}catch(Exception ex){
throw new RuntimeException("Connection Error");
}
}
public List<Guestbook> getGuestbooks(){
List<Guestbook> list = new ArrayList<>();
try {
String sql = "SELECT * FROM db_schema.guestbook";
ps = GuestbookDao().prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Long id = rs.getLong("id");
String name = rs.getString("name");
String content = rs.getString("content");
Date regdate = rs.getDate("regdate");
Guestbook guestbook = new Guestbook(id,name, content, regdate);
list.add(guestbook);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
public void addGuestbook(Guestbook guestbook){
String sql = "INSERT INTO db_schema.guestbook (name, content,regdate) VALUES (?,?,?)";
try (PreparedStatement ps = GuestbookDao().prepareStatement(sql)) {
ps.setString(1, guestbook.getName());
ps.setString(2, guestbook.getContent());
ps.setDate(3, new java.sql.Date(guestbook.getRegdate().getTime()));
ps.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}