I am currently making a program where I can delete certain entries in a database. I can do it, but I wanted to add a JOptionPane Screen for when it can or cannot find it (so when the name isn't found it should not be found and display a message saying it can't be found). I tried using a result statement but that doesn't seem to work. If anyone knows how to do it please comment on how to do so!
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<Cookbook > recipes = new ArrayList();
String name = txtName.getText();
try {
String url = "jdbc:derby://localhost:1527/Cookbook";
Connection conn = DriverManager.getConnection(url);
String query = "DELETE from RECIPES WHERE NAME = ?";
PreparedStatement pst = conn.prepareStatement(query);
pst.setString(1, name);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, name + " was sucessfully deleted");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "was not found or could not be deleted");
}
Quoting the javadoc of executeUpdate()
:
Returns:
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
So:
String url = "jdbc:derby://localhost:1527/Cookbook";
try (Connection conn = DriverManager.getConnection(url)) {
String query = "DELETE from RECIPES WHERE NAME = ?";
try (PreparedStatement pst = conn.prepareStatement(query)) {
pst.setString(1, name);
int rowCount = pst.executeUpdate();
if (rowCount == 0) {
JOptionPane.showMessageDialog(null, "'" + name + "' was not found");
} else if (rowCount == 1) {
JOptionPane.showMessageDialog(null, "'" + name + "' was successfully deleted");
} else { // cannot happen if `NAME` has unique index in the database
JOptionPane.showMessageDialog(null, rowCount + " recipes named '" + name + "' were deleted");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "something went wrong: " + e);
}