如何使用结果集更新 JDBC 中的值

How to update values in JDBC using Resultset

我想使用 ResultsSet 将所有 thd "id" 的值更改为 int k。

我有 errors-null 异常。

我在 updateInt("ID",k);

处收到错误

错误: "Cannot suppress a null exception. Self-suppression not permitted"

int k=1;
try {
    Class.forName("org.apache.derby.jdbc.ClientDriver");
    String  urlCn="jdbc:derby://localhost:1527/myDb";
    Connection   cn = DriverManager.getConnection(urlCn, "omer", "1234");
    Statement stmt = cn.createStatement();
    String sql = "SELECT * FROM QUESTIONS";
    ResultSet rs = stmt.executeQuery(sql);
    while (rs.next()) {
        if(rs.getInt("ID")!=k)
            rs.updateInt("ID", k);
        k++;
    }
    rs.close();
    cn.close();
}
catch (ClassNotFoundException ex) {
    Logger.getLogger(addQuestion.class.getName()).log(Level.SEVERE, null, ex);
}           
catch (SQLException ex) {
    Logger.getLogger(addQuestion.class.getName()).log(Level.SEVERE, null, ex);
}

尝试像这样将 updateRow() 添加到您的代码中:

   rs.beforeFirst();
   while (rs.next()) {
     if(rs.getInt("ID")!=k){
      rs.updateInt("ID", k);
      rs.updateRow();
       k++;
       }
     }

并尝试将 rs.first(); 替换为 rs.beforeFirst();
试着看看 link

我找到了一个解决方案,使用另一种方法,它的工作,没有结果集。

        int k=1;
        int oldId=1;
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            String  urlCn="jdbc:derby://localhost:1527/myDb";
            Connection   cn = DriverManager.getConnection(urlCn, "omer", "1234");
            Statement stmt = cn.createStatement();
            String sql = "SELECT * FROM QUESTIONS";
            ResultSet rs = stmt.executeQuery(sql);
            PreparedStatement st;
            while (rs.next()) {
                st = cn.prepareStatement("update QUESTIONS set id = ? where id = ?");
                oldId=rs.getInt("id");
                if(oldId!=k){
                    st.setInt(1,k);
                    st.setInt(2,oldId);
                    st.executeUpdate(); 
                }
                k++;
            }
            rs.close();
            cn.close();
        }
        catch (ClassNotFoundException ex) {
            Logger.getLogger(addQuestion.class.getName()).log(Level.SEVERE, null, ex);
        }           
        catch (SQLException ex) {
            Logger.getLogger(addQuestion.class.getName()).log(Level.SEVERE, null, ex);
        }