-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask4.java
More file actions
43 lines (37 loc) · 1.52 KB
/
Copy pathTask4.java
File metadata and controls
43 lines (37 loc) · 1.52 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
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
class ReportDAO {
private DataSource dataSource;
public List<ReportEntry> fetchMonthlyReport(String accountId,
int month, int year)
throws SQLException {
// FIX: try-with-resources closes PreparedStatement and Connection even when query execution/mapping fails.
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(
"SELECT * FROM report_entries " +
"WHERE account_id = ? AND MONTH(entry_date) = ? " +
"AND YEAR(entry_date) = ?"
)) {
ps.setString(1, accountId);
ps.setInt(2, month);
ps.setInt(3, year);
List<ReportEntry> entries = new ArrayList<>();
// FIX: Closing ResultSet in nested try-with-resources ensures closure order: ResultSet -> PreparedStatement -> Connection.
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
entries.add(mapRow(rs));
}
}
return entries;
}
}
private ReportEntry mapRow(ResultSet rs) throws SQLException {
// Existing mapping logic remains unchanged.
return new ReportEntry();
}
}