Transaction 2.0

This commit is contained in:
Imbus 2024-02-09 09:24:55 +01:00
parent 92441ad91f
commit 4a863bc14e

View file

@ -213,27 +213,46 @@ public Show getShowData(String movie, String date) {
return null;
}
ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE username = '" + username + "'");
try (PreparedStatement userQuery = conn.prepareStatement("SELECT * FROM Users WHERE username = ?");
PreparedStatement showingQuery = conn.prepareStatement("SELECT * FROM Showings JOIN Movies ON Showings.movie_id = Movies.movie_id WHERE name = ? AND show_date = ?");
PreparedStatement reservationInsert = conn.prepareStatement("INSERT INTO Reservations (user_id, showing_id) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) {
userQuery.setString(1, username);
try (ResultSet rs = userQuery.executeQuery()) {
if (rs.next()) {
int user_id = rs.getInt("id");
rs = stmt.executeQuery("SELECT * FROM Showings JOIN Movies ON Showings.movie_id = Movies.movie_id WHERE name = '" + movie + "' AND show_date = '" + date + "'");
if (rs.next()) {
System.out.println("Adding reservation");
int showing_id = rs.getInt("showing_id");
String theater = rs.getString("theater_id");
stmt.executeUpdate("INSERT INTO Reservations (user_id, showing_id) VALUES (" + user_id + ", " + showing_id + ")");
System.out.println("Reservation added");
showingQuery.setString(1, movie);
showingQuery.setString(2, date);
try (ResultSet showingRs = showingQuery.executeQuery()) {
if (showingRs.next()) {
// Getting the data from the showing query
int showing_id = showingRs.getInt("showing_id");
String theater = showingRs.getString("theater_id");
// Preparing the reservation insert with the data previously retrieved
reservationInsert.setInt(1, user_id);
reservationInsert.setInt(2, showing_id);
reservationInsert.executeUpdate();
// Committing the transaction and getting the generated keys
conn.commit();
conn.setAutoCommit(true);
int bookingId = stmt.getGeneratedKeys().getInt(1);
// Getting the generated keys, if any
try (ResultSet generatedKeys = reservationInsert.getGeneratedKeys()) {
if (generatedKeys.next()) {
int bookingId = generatedKeys.getInt(1);
return new Reservation(bookingId, movie, date, theater);
}
rs.close();
}
else {
}
}
} else {
System.err.println(String.format("addReservation: user %s not found", username));
}
conn.commit();
}
}
} catch (SQLException e) {
try {
conn.rollback();
@ -245,6 +264,7 @@ public Show getShowData(String movie, String date) {
return null;
}
public ArrayList<Reservation> getReservations(String username) {
ArrayList<Reservation> reservations = new ArrayList<Reservation>();