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
|
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BusinessCardManagerDao {
private static String dbUrl = "jdbc:mysql://localhost:3306/businesscard?serverTimezone=UTC";
private static String dbUser = "employee";
private static String dbPassward = "connect123!@#";
public List<BusinessCard> searchBusinessCard(String keyword){
List<BusinessCard> list = new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
String sql = "SELECT name, phone, companyName FROM businesscard WHERE name LIKE ?";
try(Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassward);
PreparedStatement ps = conn.prepareStatement(sql);
){
ps.setString(1,keyword+"%"); //like연산시 주의점 "'"+keyword+"%'" 로 하면 인식을 못한다.
ResultSet rs = ps.executeQuery();
while(rs.next()) {
String name = rs.getString("name");
String phone =rs.getString("phone");
String companyName = rs.getString("companyName");
BusinessCard businessCard = new BusinessCard(name, phone, companyName);
list.add(businessCard);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public BusinessCard addBusinessCard(BusinessCard businessCard){
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
String sql = "insert into businesscard value(?,?,?,?)";
try(Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassward);
PreparedStatement ps = conn.prepareStatement(sql);
) {
ps.setString(1, businessCard.getName());
ps.setString(2, businessCard.getPhone());
ps.setString(3, businessCard.getCompanyName());
ps.setDate(4,new java.sql.Date(businessCard.getCreateDate().getTime()));
//주의점 setDate의 date는 java.sql.Date이다. java.util.Date.getTime()을 하면 해결이 된다.
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
cs |
주의점 !
22행 : like 연산시 주의점
51행: setDate시 주의점
'DB관련 > mysql' 카테고리의 다른 글
IF 문 (0) | 2021.01.14 |
---|---|
시저 암호 (0) | 2020.12.29 |
DDL (0) | 2020.11.25 |
mysql -- join (0) | 2020.11.25 |
DML - insert, update ,delete (0) | 2020.11.25 |