-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJdbcAccountRepository.java
More file actions
108 lines (78 loc) · 2.92 KB
/
JdbcAccountRepository.java
File metadata and controls
108 lines (78 loc) · 2.92 KB
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
package com.example;
import javax.sql.DataSource;
import java.sql.*;
public class JdbcAccountRepository implements AccountRepository {
private final DataSource ds;
public JdbcAccountRepository(DataSource ds) {
this.ds = ds;
}
@Override
public boolean login(String username, String password) {
String sql = "SELECT 1 FROM account WHERE name = ? AND password = ?";
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, username);
ps.setString(2, password);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public long create(String first, String last, String ssn, String password) {
String sql = "INSERT INTO account(first_name, last_name, ssn, password) VALUES (?, ?, ?, ?)";
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, first);
ps.setString(2, last);
ps.setString(3, ssn);
ps.setString(4, password);
ps.executeUpdate();
ResultSet keys = ps.getGeneratedKeys();
if (keys.next()) {
return keys.getLong(1);
}
throw new RuntimeException("No ID returned!");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean updatePassword(int userId, String newPassword) {
String sql = "UPDATE account SET password = ? WHERE user_id = ?";
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, newPassword);
ps.setInt(2, userId);
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean delete(int userId) {
String sql = "DELETE FROM account WHERE user_id = ?";
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, userId);
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean exists(int userId) {
String sql = "SELECT 1 FROM account WHERE user_id = ?";
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, userId);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}