java - 如何显示条目是否在数据库中?
问题描述
我目前正在制作一个程序,我可以在其中删除数据库中的某些条目。我可以做到,但我想添加一个 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");
}
解决方案
引用 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);
}
推荐阅读
- sql - 合并表格中的多行?
- paypal - PayPal 智能按钮 - 如何预先选择用户国家进行计费
- security - 需要注意的 Lua 命令/语句列表?
- php - 通过 PHP 中的 Curl URL 获取响应
- react-native - 暗模式不起作用 React Navigation React Native
- node.js - 禁止jobs.batch:用户''“system:serviceaccount:default:default”无法在命名空间“default”中的API组“batch”中列出资源“jobs”
- ffmpeg - ffmpeg 4.3.1中的电影过滤器是否支持png格式的图片
- c# - 删除编辑表单中的图像选项
- c++ - 如何为 16x2 LCD 编写 Cout<< Like 打印功能?
- javascript - Vue.js 组件中的多个引用