Java 如何显示条目是否在数据库中?
我目前正在制作一个程序,可以删除数据库中的某些条目。我可以这样做,但我想添加一个JOptionPane屏幕,以便在它可以或无法找到它时显示它(因此,当找不到名称时,不应该找到它,并显示一条消息说找不到它)。我尝试使用结果语句,但似乎不起作用。如果有人知道怎么做,请评论怎么做Java 如何显示条目是否在数据库中?,java,sql,database,joptionpane,Java,Sql,Database,Joptionpane,我目前正在制作一个程序,可以删除数据库中的某些条目。我可以这样做,但我想添加一个JOptionPane屏幕,以便在它可以或无法找到它时显示它(因此,当找不到名称时,不应该找到它,并显示一条消息说找不到它)。我尝试使用结果语句,但似乎不起作用。如果有人知道怎么做,请评论怎么做 private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
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");
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt){
ArrayList recipes=新的ArrayList();
String name=txtName.getText();
试一试{
String url=“jdbc:derby://localhost:1527/Cookbook";
连接conn=DriverManager.getConnection(url);
String query=“从配方中删除,其中名称=?”;
PreparedStatement pst=conn.prepareStatement(查询);
pst.setString(1,名称);
pst.executeUpdate();
showMessageDialog(null,名称+“已成功删除”);
}捕获(例外e){
showMessageDialog(null,“未找到或无法删除”);
}
引用javadoc:
返回:
对于SQL数据操作语言(DML)语句,(1)行计数,或者(2)对于不返回任何内容的SQL语句,行计数为0
因此:
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);
}