Transport Service
Transport Service
import entities.Transport;
import entities.TransportType;
import utils.MyConnection;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Override
public void create(Transport transport) throws SQLException {
String query = "INSERT INTO transport (type, companyName,
departureLocation, arrivalLocation, departureTime, arrivalTime, price, isElectric,
availability) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
// Execute update
ps.executeUpdate();
System.out.println("Transport created");
}
@Override
public void update(Transport transport) throws SQLException {
String query = "UPDATE transport SET type = ?, companyName = ?,
departureLocation = ?, arrivalLocation = ?, departureTime = ?, arrivalTime = ?,
price = ?, isElectric = ?, availability = ? WHERE IdTransport = ?";
PreparedStatement ps = cnx.prepareStatement(query);
@Override
public void delete(Transport transport) throws SQLException {
String deleteReservationsQuery = "DELETE FROM reservation WHERE idTransport
= ?";
PreparedStatement ps1 = cnx.prepareStatement(deleteReservationsQuery);
ps1.setInt(1, transport.getIdTransport());
ps1.executeUpdate();
@Override
public List<Transport> readAll() throws SQLException {
List<Transport> transports = new ArrayList<>();
String query = "SELECT * FROM transport";
Statement st = cnx.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
// Retrieve data for each transport
String typeStr = rs.getString("type");
String companyName = rs.getString("companyName");
String departureLocation = rs.getString("departureLocation");
String arrivalLocation = rs.getString("arrivalLocation");
String departureTime = rs.getString("departureTime");
String arrivalTime = rs.getString("arrivalTime");
double price = rs.getDouble("price");
boolean isElectric = rs.getBoolean("isElectric");
boolean availability = rs.getBoolean("availability");
if (dateString != null) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
transportDate = sdf.parse(dateString); // Convert the string
to Date
} catch (Exception e) {
e.printStackTrace(); // Handle the exception in case of an
invalid date format
}
}
return transports;
}