Search code examples
javasqldatabasejdbcresultset

How to update values in JDBC using Resultset


I want to chang all thd "id"'s values to int k, using ResultsSet.

I am having errors-null exception.

I get the error at the updateInt("ID",k);

Error: "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);
}

Solution

  • I find a solution using another way,ITS WORK, without the 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);
            }