首页 > 解决方案 > 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无法转换为结果集”。

标签: javasqlsqlitesql-delete

解决方案


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);
    }
}

推荐阅读