简体   繁体   中英

SQLException: query does not return results

I am doing a project in Java Swing and using SQLite as my database. This is the function I wrote for deleting a record from the Room table in my database.

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. I have tried to use pst.executeUpdate() as suggested in other answers but it says "int cannot be converted into resultset".

A DELETE statement does not return a result set. You should call method executeUpdate rather than method executeQuery .

Also, you can use place holders with a PreparedStatement .

Also you should use 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM