在通过ResultSet反向检索数据时出现NullPointerException

时间:2015-11-16 12:22:02

标签: java sql oracle jdbc

Statement createStatement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet executeQuery = createStatement.executeQuery("select * from stu");
executeQuery.afterLast();
while (executeQuery.previous()) {   //15th line<--exception occurs at this place after first record is retrieved
    int rollno = executeQuery.getInt(1);
    System.out.println("rollno " + rollno + " name " + executeQuery.getString(2));
    if (rollno == 1) {
        if (createStatement.executeUpdate("update stu set name=" + "'vinay'" + "where rollno=1") >= 1) {
            System.out.println("row updated");      
        }
    }
}

输出:

  

rollno 1 name vinay

行更新

//检索到第一条记录后会抛出异常

Exception in thread "main" java.lang.NullPointerException
   at oracle.jdbc.driver.ScrollableResultSet.previous(ScrollableResultSet.java:630)
   at com.vk.db.ScrollableResultSet.main(ScrollableResultSet.java:15)

2 个答案:

答案 0 :(得分:1)

错误原因是回收语句对象。试试这段代码/

   Statement createStatement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet executeQuery = createStatement.executeQuery("select id, name from stu");       
        executeQuery.afterLast();
        while (executeQuery.previous()) {   
            int rollno = executeQuery.getInt("id");
            System.out.println("rollno " + executeQuery.getString("id") + " name " + executeQuery.getString("name"));
            if (rollno == 1) {
                executeQuery.updateString("NAME", "new value");
                executeQuery.updateRow();
            }
        }

请注意。查询无法使用SELECT * from table

答案 1 :(得分:0)

尝试改变

 executeQuery.afterLast(); 

executeQuery.last();                   

或使用像

这样的while循环
 while (executeQuery.next()) {
   code....
    }