-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudentDAO.java
More file actions
86 lines (69 loc) · 2.89 KB
/
Copy pathStudentDAO.java
File metadata and controls
86 lines (69 loc) · 2.89 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
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StudentDAO {
public StudentDTO authenticateStudent(String studentId, String pin) {
String sql = "SELECT student_id, name, pin_hash, salt, balance FROM students WHERE student_id = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, studentId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
String storedHash = rs.getString("pin_hash");
String salt = rs.getString("salt");
if (SecurityUtil.verifyPassword(pin, salt, storedHash)) {
return new StudentDTO(
rs.getString("student_id"),
rs.getString("name"),
rs.getBigDecimal("balance")
);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public BigDecimal getBalance(String studentId) {
String sql = "SELECT balance FROM students WHERE student_id = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, studentId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getBigDecimal("balance");
}
} catch (SQLException e) {
e.printStackTrace();
}
return BigDecimal.ZERO;
}
public boolean updateBalance(String studentId, BigDecimal newBalance) {
String sql = "UPDATE students SET balance = ? WHERE student_id = ? AND balance >= 0";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setBigDecimal(1, newBalance);
stmt.setString(2, studentId);
return stmt.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean addWeeklyAllowance(String studentId) {
String sql = "UPDATE students SET balance = balance + weekly_allowance, " +
"last_allowance_date = CURDATE() " +
"WHERE student_id = ? AND " +
"(last_allowance_date IS NULL OR last_allowance_date < CURDATE() - INTERVAL 7 DAY)";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, studentId);
return stmt.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}