【问题标题】:Getting value of only 1 random row and set the values to a class仅获取 1 个随机行的值并将值设置为一个类
【发布时间】:2018-01-07 12:01:11
【问题描述】:

我一直在尝试从我的表中设置随机行的值,但是当我尝试从我的 servlet 中检索它时它一直给我一个空值。

这是我检索随机行并将值设置到我的班级的代码。 sq 是表的名称。

public Question getQuestion() throws Exception{
    System.out.println("Getting the questions");

    Question question = null;
    try{
        String selectStatement = "select * from sq order by rand() limit 1";
        PreparedStatement prepStmt = con.prepareStatement(selectStatement);
        ResultSet rs = prepStmt.executeQuery();

        if(rs.next()){
            Question myquestion = new Question();
            myquestion.setQid(rs.getInt("QID"));
            myquestion.setQuestion(rs.getString("question"));
            //System.out.println(rs.getString("question"));
            System.out.println(myquestion.getQuestion());
        }

    }catch(Exception ex){
        throw new Exception("Error:" + ex.getMessage());
    }
    return question;
}

它在这里打印出问题,但它在我的 servlet 中给了我一个空值。

try{
            Database myDatabase = new Database();
            Question question = myDatabase.getQuestion();
            if(question != null){
                HttpSession session = request.getSession(true);
                session.setAttribute("secquestion", question);
                request.getRequestDispatcher("SecQn.jsp").forward(request, response);
            }else{
                System.out.println("ERROR");
            }
            //request.getRequestDispatcher("Home.jsp").forward(request, response);
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
    }

当我之前已经设置了值时,它会打印出 ERROR,这意味着问题的值为 null。如何正确设置值?还是我的代码有什么问题?


解决了错误。这是最新的更新代码。

public Question getQuestion() throws Exception{
    System.out.println("Getting the questions");

    Question question = null;
    try{
        String selectStatement = "select * from sq order by rand() limit 1";
        PreparedStatement prepStmt = con.prepareStatement(selectStatement);
        ResultSet rs = prepStmt.executeQuery();
        if(rs.next()){
            question = new Question();
            question.setQid(rs.getInt("QID"));
            question.setQuestion(rs.getString("question"));
            System.out.println(question.getQuestion());
        }       
    }catch(Exception ex){
        throw new Exception("Error:" + ex.getMessage());
    }
    return question;
}

【问题讨论】:

    标签: java mysql jsp session servlets


    【解决方案1】:

    getQuestion() 方法中,您正在返回问题,但您从未为其分配任何值。 您应该返回 myquestion ,或者在返回之前分配。

    question = myquestion ;
    

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多