获取仅1个随机行的值并将值设置为类

时间:2017-07-31 19:33:22

标签: java mysql jsp session servlets

我一直在尝试从我的表中设置一个随机行的值,但是当我尝试从我的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;
}

1 个答案:

答案 0 :(得分:0)

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

question = myquestion ;