java - SQLException:查询不返回结果
问题描述
我正在用 Java Swing 做一个项目,并使用 SQLite 作为我的数据库。这是我为从数据库的 Room 表中删除记录而编写的函数。
public void Delete() {
String room_code = jTextField5.getText();
String sql = "DELETE FROM Room WHERE room_code = '" + room_code + "'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Room Deleted Successfully");
}
else {
JOptionPane.showMessageDialog(null, "Invalid Room Code");
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
但是,我遇到了以下异常: SQLException:查询不返回结果。我已尝试按照其他答案中的建议使用 pst.executeUpdate() ,但它说“int无法转换为结果集”。
解决方案
DELETE
语句不返回结果集。您应该调用方法executeUpdate而不是 method executeQuery
。
此外,您可以将占位符与PreparedStatement一起使用。
你也应该使用try-with-resources
考虑以下代码。
public void Delete() {
String room_code = jTextField5.getText();
String sql = "DELETE FROM Room WHERE room_code = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(room_code);
int count = ps.executeUpdate();
if (count > 0) {
JOptionPane.showMessageDialog(null, "Room Deleted Successfully");
}
else {
JOptionPane.showMessageDialog(null, "Invalid Room Code");
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
推荐阅读
- javascript - 使用 iframe 获取鼠标在页面上的点击位置
- python - 显示被禁止的用户 discord.py
- java - 在 Reactor 中更新对象的状态
- python - 循环一系列字典以转换为 DataFrame
- python - 具有 sqlalchemy 的服务器表的通用数据库函数
- java - 无法在 Android 11 (Wi-Fi Direct) 上使用 WifiP2pManager.setDeviceName
- python - 在python的txt文件中添加两个时间戳的差异的问题
- r - ggplot:如何使用列名作为 x 轴标签和值作为 y 轴
- sql - SQL 将行转换为一列
- r - 百分比堆积条形图中的工具提示