Transaction

This commit is contained in:
Imbus 2024-02-09 09:17:22 +01:00
parent 570b0c319b
commit 92441ad91f

View file

@ -204,8 +204,15 @@ public Show getShowData(String movie, String date) {
System.out.println("Adding reservation for " + username + " for " + movie + " on " + date);
try {
Statement stmt = conn.createStatement();
try(Statement stmt = conn.createStatement()) {
conn.setAutoCommit(false);
Show s = getShowData(movie, date);
if (s.getSeats() <= 0) {
System.err.println("addReservation: no free seats for " + movie + " on " + date);
return null;
}
ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE username = '" + username + "'");
if (rs.next()) {
int user_id = rs.getInt("id");
@ -216,14 +223,23 @@ public Show getShowData(String movie, String date) {
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");
conn.commit();
conn.setAutoCommit(true);
int bookingId = stmt.getGeneratedKeys().getInt(1);
return new Reservation(bookingId, movie, date, theater);
}
rs.close();
}
else {
System.err.println(String.format("addReservation: user %s not found", username));
}
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e2) {
e2.printStackTrace();
}
e.printStackTrace();
}
return null;