#java #sql
Вопрос:
У меня есть методы «addAppointment» и «updateAppointment», которые оба используют одни и те же параметры.
public static void addAppointment(String title, String description, String location, String type, LocalDateTime start, LocalDateTime end, int customerID, int userID, int contactID)
{
try { String sqlAddAppt = "INSERT INTO appointments VALUES (NULL, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, ?, ?, ?)";
PreparedStatement ps = JDBC.getConnection().prepareStatement(sqlAddAppt);
ps.setString(1, title);
ps.setString(2, description);
ps.setString(3, location);
ps.setString(4, type);
ps.setTimestamp(5, Timestamp.valueOf(start));
ps.setTimestamp(6, Timestamp.valueOf(end));
ps.setInt(7, customerID);
ps.setInt(8, userID);
ps.setInt(9, contactID);
ps.execute();
}
catch (SQLException e) {
e.printStackTrace(); }}
public static void updateAppointment(String title, String description, String location, String type, LocalDateTime start, LocalDateTime end, int customerID, int userID, int contactID) {
try {
String sqlUpdate = "UPDATE appointments SET Title=?, Description=?, Location=?, Type=?, Start=?, End=?, Customer_ID=?, User_ID=?, Contact_ID=? WHERE Appointment_ID = ?;";
PreparedStatement ps = JDBC.getConnection().prepareStatement(sqlUpdate);
ps.setString(1, title);
ps.setString(2, description);
ps.setString(3, location);
ps.setString(4, type);
ps.setTimestamp(5, Timestamp.valueOf(start));
ps.setTimestamp(6, Timestamp.valueOf(end));
ps.setInt(7, customerID);
ps.setInt(8, userID);
ps.setInt(9, contactID);
ps.execute(); } catch (SQLException e) {
e.printStackTrace(); }}
Я вызываю методы таким же образом, используя :
DBAppointments.updateAppointment(title, description, location, type, startTimeUTC.toLocalDateTime(), endTimeUTC.toLocalDateTime(), customerID.getCustomerID(), userID.getUserID(), contact.getContactID());
DBAppointments.addAppointment(title, description, location, type, startTimeUTC.toLocalDateTime(), endTimeUTC.toLocalDateTime(), customerID.getCustomerID(), userID.getUserID(), contact.getContactID());
«addAppointment» работает отлично и вставляется правильно, но когда я пытаюсь использовать метод обновления, он не возвращает никаких ошибок, но также не обновляет базу данных. Есть идеи?
Комментарии:
1. Что обрабатывалось, когда вы вызывали updateAppointment? Он запускал exceucte ()?
2. Кажется, что Appointment_ID не задан
3. Проверьте, совершена ли транзакция явно или неявно. Кроме того, имеет смысл включить отладку и ведение журнала запросов SQL с отображением значения параметра. Это поможет в дальнейшем диагностировать проблему. Кроме того, вы можете прочитать журналы БД и посмотреть, что видит БД
4. @HanhNguyen Спасибо за ответ! Я извлекаю информацию из назначения, уже находящегося в базе данных, как переменную «selectedAppointment». Я установил его, используя «selectedAppointment.getAppointmentID» вместо «appointmentIDText», и теперь он обновляется правильно. Спасибо за подсказку!
Ответ №1:
Вы можете использовать Hibernate и JDBC, что является более чистым способом выполнения операций CRUD в вашей БД. Это может быть совсем другой подход, если вы его раньше не видели, однако я предлагаю вам ознакомиться с этим подходом, потому что в настоящее время это стандартный способ выполнения операций с БД.
Начните с определения вашей сущности и интерфейса, затем добавьте контроллер для выполнения ваших операций
@Entity('TableName')
public class Person {
@Column('table_column_name')
String title;
@Column('table_column_name')
String description;
@Column('table_column_name')
String location;
@Column('table_column_name')
String type;
@Column('table_column_name')
LocalDateTime start;
@Column('table_column_name')
LocalDateTime end;
@Column('table_column_name')
int customerID;
@Column('table_column_name')
int userID;
@Column('table_column_name')
int contactID;
}
This person class is basically the column headings of your table in your
database
Вы создадите интерфейс, в котором будут размещаться операции с БД
public interface PersonRepository extends CrudRepository<Person, Long> {
/*This will contain all the database operations you want to perform. By
default, it contains the CRUD operations and if you will be performing
CRUD operations only, you don't need to add anything*/
}
You will then have a controller where you will perform your crud operations
@RestController
public class Controller {
@Autowired
PersonRepository personRepo;
@PostMapping("/save")
public void addAppointment(Person person) {
personRepo.save(person);
}
@PutMapping("/update")
public void updateAppointment(int personID, String description, int customerID) {
//retrieve the user whose appointment you want to update then update the relevant fields and save user;
Person person = personRepo.findById(personID);
person.setDescription(description);
person.setCustomerID(customerID);
personRepo.save(person);
}
}
Подробнее об этом можно прочитать здесь