Medical-Practice/src/main/java/at/ionas999/health/services/PatientService.java

79 lines
2.7 KiB
Java

package at.ionas999.health.services;
import at.ionas999.health.model.Patient;
import java.sql.*;
import java.util.ArrayList;
public class PatientService extends DatabaseUtilsBase implements TableCreation {
public PatientService() {
this.tableCreationArrayList.add(this);
}
@Override
public void CreateTable(Connection connection) throws SQLException {
String createTableSmt = "CREATE TABLE Patient (\n" +
" name VARCHAR(255) NOT NULL PRIMARY KEY,\n" +
" appointment TIMESTAMP,\n" +
" isEmergency BOOLEAN\n" +
")";
connection.createStatement().executeQuery(createTableSmt);
}
public boolean AddPatient(Patient patient) {
try (Connection connection = this.GetDbConnection()) {
String insertStmt = "INSERT INTO Patient (name, appointment, isEmergency) VALUES (?, ?, ?)";
PreparedStatement prepStmt = connection.prepareStatement(insertStmt);
prepStmt.setString(1, patient.getName());
prepStmt.setTimestamp(2, Timestamp.valueOf(patient.getAppointment()));
prepStmt.setBoolean(3, patient.isEmergency());
int updates = prepStmt.executeUpdate();
prepStmt.close();
return updates == 1;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void DeletePatient(String name) {
try (Connection connection = this.GetDbConnection()) {
String stmt = "DELETE FROM Patient WHERE name = ?";
PreparedStatement prepStmt = connection.prepareStatement(stmt);
prepStmt.setString(1, name);
int updates = prepStmt.executeUpdate();
prepStmt.close();
if (updates != 1) {
throw new RuntimeException("Failed to delete patient with name: " + name);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public ArrayList<Patient> GetAllPatients() {
ArrayList<Patient> patients = new ArrayList<>();
try (Connection connection = this.GetDbConnection()) {
String stmt = "SELECT * FROM Patient";
PreparedStatement prepStmt = connection.prepareStatement(stmt);
ResultSet rs = prepStmt.executeQuery();
while (rs.next()) {
Patient p = new Patient(rs.getString(1),
rs.getTimestamp(2).toLocalDateTime(),
rs.getBoolean(3));
patients.add(p);
}
prepStmt.close();
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return patients;
}
}