SQLException: 查询没有 return 个结果
SQLException: query does not return results
我正在 Java Swing 中做一个项目并使用 SQLite 作为我的数据库。
这是我为从我的数据库中的 table 房间删除一条记录而编写的函数。
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:查询没有 return 结果。
我曾尝试按照其他答案中的建议使用 pst.executeUpdate(),但它说“int cannot be converted into resultset”。
一个DELETE
语句没有return一个结果集。您应该调用方法 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);
}
}
我正在 Java Swing 中做一个项目并使用 SQLite 作为我的数据库。 这是我为从我的数据库中的 table 房间删除一条记录而编写的函数。
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:查询没有 return 结果。 我曾尝试按照其他答案中的建议使用 pst.executeUpdate(),但它说“int cannot be converted into resultset”。
一个DELETE
语句没有return一个结果集。您应该调用方法 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);
}
}