-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJdbcMoonMissionRepository.java
More file actions
56 lines (48 loc) · 1.79 KB
/
JdbcMoonMissionRepository.java
File metadata and controls
56 lines (48 loc) · 1.79 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
package com.example;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class JdbcMoonMissionRepository implements MoonMissionRepository {
private final DataSource dataSource;
public JdbcMoonMissionRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public List<String> findAllSpacecraftNames() throws SQLException {
List<String> names = new ArrayList<>();
String sql = "SELECT spacecraft FROM moon_mission";
try (Connection connection = dataSource.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
names.add(rs.getString("spacecraft"));
}
}
return names;
}
@Override
public ResultSet findMissionById(long missionId, Connection connection) throws SQLException {
String sql = "SELECT * FROM moon_mission WHERE mission_id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setLong(1, missionId);
return stmt.executeQuery();
}
@Override
public int countMissionsByYear(int year) throws SQLException {
String sql = "SELECT COUNT(*) FROM moon_mission WHERE YEAR(launch_date) = ?";
try (Connection connection = dataSource.getConnection();
PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setInt(1, year);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getInt(1);
}
return 0;
}
}
}
}