0
我一直在嘗試從我的表中設置一個隨機行的值,但它在嘗試檢索時一直給我一個空值它來自我的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());
}
}
它打印出錯誤,這意味着當我已經設置了以前的值時,問題的值爲空。如何正確設置值?或者我的代碼有什麼問題?
解決了錯誤。這是最新的更新代碼。
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;
}