Here I have my method that deletes the customer given the id. It works, but if you give it an invalid id nothing happens and I want to tell the user that the delete failed. I tried using an if statement with executeQuery(), but I realized it returns false even if the delete was successful not just when there are no rows affected.
private static final String DELETE = "DELETE FROM customers WHERE customer_id = ?";
public void deleteByID(int id) {
try(PreparedStatement ps = this.connection.prepareStatement(DELETE)) {
ps.setInt(1, id);
ps.execute();
} catch(SQLException e) {
e.printStackTrace();
}
}
You can use PreparedStatement.executeUpdate()
which will return number of rows affected. If the return value is < 1, no rows were deleted. Based on that you can show the error to the user.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.