gpt4 book ai didi

java - 如何显示条目是否在数据库中?

转载 作者:行者123 更新时间:2023-12-01 22:08:15 25 4
gpt4 key购买 nike

我目前正在制作一个程序,可以在其中删除数据库中的某些条目。我可以做到这一点,但我想添加一个 JOptionPane 屏幕,以便它何时可以找到它或无法找到它(因此,当未找到名称时,不应找到它并显示一条消息说找不到它)。我尝试使用结果语句,但这似乎不起作用。如果有人知道如何做,请评论如何做!

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");
}

最佳答案

引用executeUpdate()的javadoc :

Returns:

either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

所以:

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);
}

关于java - 如何显示条目是否在数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58677499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com