有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Mysql Java Derby Netbeans不允许使用“deleteRow”,因为ResultSet不是可更新的ResultSet

我试图删除一行,但它不允许我,它说“'deleteRow'不允许,因为结果集不是可更新的结果集”。这是我的代码:

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

}

我做错了什么?如有任何建议,将不胜感激。提前谢谢

这就是我创建表的方式,并添加了给定的建议,但仍然得到相同的错误:

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

共 (1) 个答案

  1. # 1 楼答案

    来自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
    

    因此,在创建语句时,必须设置ResultSet.CONCUR_UPDATABLE属性