如何使用Resultset

时间:2016-01-28 17:42:09

标签: java sql database jdbc resultset

我想使用ResultsSet将所有“id”的值转换为int k。

我有错误 - 空例外。

我在updateInt(“ID”,k);

得到错误

错误: “无法抑制空异常。不允许自我抑制”

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

2 个答案:

答案 0 :(得分:0)

尝试将updateRow()添加到您的代码中,如下所示:

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

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

进行监督

答案 1 :(得分:0)

我使用另一种方式找到了一个解决方案,ITS WORK,没有Resultset。

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