游标状态无效 - 从sql表中检索整数值时没有当前行

时间:2017-02-05 15:20:46

标签: java resultset

我一直在搜索这个但没有解决我的问题,我试图从sql表中获取注册用户的id(即INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY),名为" USERS",在调用int _id = rs2.getInt("UserID");时,它会抛出异常:Invalid cursor state - no current row. 这是我到目前为止:

Servlet.java中的

try{
    stmt = conn.prepareStatement(UAppConstants.SELECT_USERID_BY_NAME);
    System.out.println("1");
    stmt.setString(1, _username);
    System.out.println("2");
    ResultSet rs2 = stmt.executeQuery();
    System.out.println("3");
    int _id = rs2.getInt("UserID"); //exception here
    System.out.println("the registered user id is" +  _id);

}catch (SQLException e) {
        System.err.println(e.getMessage()); // print error
}

在UAppConstants.java中:

public final String CREATE_USERS_TABLE = "CREATE TABLE USERS (UserID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) PRIMARY KEY,username varchar(10) NOT NULL,password varchar(8) NOT NULL,description varchar(50) DEFAULT NULL,nickname varchar(20) NOT NULL,photo varchar(100) DEFAULT NULL)";
public final String INSERT_USER_STMT = "INSERT INTO USERS (username,password,nickname,description,photo) VALUES (?,?,?,?,?)";
public final String SELECT_USERID_BY_NAME = "SELECT UserID FROM USERS WHERE username=? ";

UserModel.java:

public class User {
private String Username, Password, Description, Photo,Nickname;//user "schema"
private int UserID;


public User(String name, String pass, String nick,String desc,String photo ) {
    Username = name;
    Password = pass;
    Description = desc;
    Photo = photo;
    Nickname = nick;
}



/* Getters & Setters */

public int getUserID() {
    return UserID;
}

public void setUserID(int uid) {
    this.UserID = uid;
}

//the rest of getters and setters

例外:

INFO: Reloading Context with name [/ExampleServletv3] is completed
        1
        2
        3
        Invalid cursor state - no current row.
有人可以指导我做什么吗? 谢谢

1 个答案:

答案 0 :(得分:0)

executeQuery之后,光标位于第一行之前。所以你还无法访问任何数据。首先,您需要调用next()将光标移动到第一行。

所以它应该是:

stmt = conn.prepareStatement(UAppConstants.SELECT_USERID_BY_NAME);
stmt.setString(1, _username);
ResultSet rs2 = stmt.executeQuery();
if (rs2.next()) {
    int _id = rs2.getInt("UserID");
    // do something with the id
} else {
    // user not found
}

以及异常处理的提示:除了使用枯燥的print语句而不是处理异常(除了非常小的消息)之外,不要重新抛出异常:

try {
    // code
} catch (SQLException e) {
    throw new RuntimeException(e);
}

通过这种方式,您可以获得包含所有嵌套异常的完整错误消息,并且还可以获得抛出异常的行。