亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何顯示條目是否在數據庫中?

如何顯示條目是否在數據庫中?

慕哥6287543 2024-01-25 15:56:05
我目前正在制作一個程序,可以在其中刪除數據庫中的某些條目。我可以做到這一點,但我想添加一個 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");    }
查看完整描述

1 回答

?
元芳怎么了

TA貢獻1798條經驗 獲得超7個贊

引用javadoc?executeUpdate()

返回:

(1)?SQL 數據操作語言 (DML) 語句的行計數或 (2) 0(不返回任何內容的 SQL 語句)

所以:

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

}


查看完整回答
反對 回復 2024-01-25
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號