有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAsql。SQLException:无效的光标状态没有当前行

当我使用ResultSet中的getString方法时,我一直遇到这个错误。我将第一个方法的返回结果集用于第二个方法。相关代码:

public ResultSet getStudentRS(){
    try{
        studentRS = s.executeQuery("SELECT * FROM Students "
                + "WHERE StudentID=210569906");
    }
    catch(SQLException error){
        System.err.println("Unable to query for getStudentRS.");
        error.printStackTrace(System.err);
        System.exit(0);
    }
    return studentRS;
}

public String getUserName(){
    try{
        while(rs.next())
            return rs.getString(1) + " " + rs.getString(2); // Exception Here
    }
    catch(SQLException error){
        System.err.println("Unable to query for getUserName.");
        error.printStackTrace(System.err);
        System.exit(0);
    }
    return "Failure";
}

非常感谢您在解决此问题时提供的任何帮助


共 (2) 个答案

  1. # 1 楼答案

    while语句后面有一个分号

    while(rs.next());
    
  2. # 2 楼答案

    请看以下代码:

    while(rs.next());
    return rs.getString(1) + " " + rs.getString(2);
    

    您将遍历所有数据,直到将光标移动到最后一行。。。然后试图获取数据。鉴于您的缩进,我怀疑您不打算在while循环结束时使用分号-这就是为什么使用大括号以及让IDE格式化代码总是很好的原因。。。这让这类事情变得显而易见。即使没有分号,我也不认为这是最好的表达方式

    我想你想要:

    if (rs.next())
    {
        return rs.getString(1) + " " + rs.getString(2);
    }
    else
    {
        // What do you want to do if there are no results?
    }