[英]SQLException: query does not return results
我正在 Java Swing 做一个项目,并使用 SQLite 作为我的数据库。 这是我写的 function,用于从我的数据库中的 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而不是方法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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.