Search code examples
javamysqlnetbeansjdbcderby

Mysql Java Derby Netbeans: 'deleteRow' not allowed because the ResultSet is not an updatable ResultSet


I'm trying delete a row but it does not allow me, it says "'deleteRow' not allowed because the ResultSet is not an updatable ResultSet". Here is my code:

public void addUserName() throws SQLException {
    rs = st.executeQuery("select NAME, prize from usernames");
    try {
        while (rs.next()) {
            String attribute2 = rs.getString("name");

            if (attribute2.equals(getName())){
                String toPrint = rs.getString(2);
                System.out.println("Welcome back " + getName());
                System.out.println("You previously won " + toPrint);
                System.out.println("Let's see if you can do any better this time :)");
                rs.deleteRow();

            }
        }

    } catch (SQLException ex) {
        Logger.getLogger(Millionaire.class.getName()).log(Level.SEVERE, null, ex);
    }

}

What am I doing wrong here? Any advise would be appreciated. Thanks in advance.

This is how I created the table, and added the advise given, but still getting the same error:

public void createTable(String tableName) {
    try {
        Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                              ResultSet.CONCUR_UPDATABLE);
        //String newTable = "millionair";

        //statement.executeUpdate("drop table if exists "+newTable);
        String sqlCreateTable = "CREATE TABLE " + tableName + " (NAME VARCHAR(50), PRIZE INT)";

        stmt.executeUpdate(sqlCreateTable);
    } catch (SQLException ex) {

        System.err.println("SQLException: " + ex.getMessage());
    }
}

Solution

  • From the docs

    A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options.

       Statement stmt = con.createStatement(
                                      ResultSet.TYPE_SCROLL_INSENSITIVE,
                                      ResultSet.CONCUR_UPDATABLE);
       ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
       // rs will be scrollable, will not show changes made by others,
       // and will be updatable
    

    So you have to set ResultSet.CONCUR_UPDATABLE property when creating a statement.