[英]SQLException: query does not return results
I am doing a project in Java Swing and using SQLite as my database.我正在 Java Swing 做一个项目,并使用 SQLite 作为我的数据库。 This is the function I wrote for deleting a record from the Room table in my database.
这是我写的 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);
}
}
However, I am met with the following Exception: SQLException: query does not return results.但是,我遇到了以下异常: SQLException:查询不返回结果。 I have tried to use pst.executeUpdate() as suggested in other answers but it says "int cannot be converted into resultset".
我已尝试按照其他答案中的建议使用 pst.executeUpdate() ,但它说“int无法转换为结果集”。
A DELETE
statement does not return a result set. DELETE
语句不返回结果集。 You should call method executeUpdate rather than method executeQuery
.您应该调用方法executeUpdate而不是方法
executeQuery
。
Also, you can use place holders with a PreparedStatement .此外,您可以将占位符与PreparedStatement一起使用。
Also you should use try-with-resources你也应该使用try-with-resources
Consider the following code.考虑以下代码。
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.