Jsp sql update query

2019-08-19 08:50发布

问题:

<%
  Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/questionaire", "root", "root");
  Statement st=con.createStatement();
  ResultSet rs=st.executeQuery("Select * from question");
  List arrlist = new ArrayList();
  while(rs.next()){
  String xa =rs.getString("display");
  if(xa.equals("1")){
  arrlist.add(rs.getString("q"));
  }
}
Collections.shuffle(arrlist); %>
<%for(int i=0;i<5;i++){
    String str = (String) arrlist.get(i);%>
    <%=str%> //1
    <%st.executeUpdate("update question set display='0' where id=?");%> //comment 2
  <br>
<%}%>

This is my code.I have some questions which are displayed,then I shuffle them and randomly select 5 questions.The 5 randomly selected questions need to be given display='0' as can be seen in comment 2.How do I do it.I need to pass the id that str has to the database.Could anyone help?

回答1:

1.) When selecting your questions you should not only "remember" the question-text but also the id. Why not create a new "Question"-class that can keep both values and possibly some more information(correct answer etc.).

public class Question {

    private int id;
    private String questionText;
    private String answer;
    private boolean display=false;

    public Question(int id,String questionText,String answer) {
        this.id = id;
        this.questionText = questionText;
        this.answer= answer;
    }

    public int getId() {
        return id;
    }

    public String getQuestionText() {
        return questionText;
    }

    public String getAnswer() {
        return answer;
    }

public boolean getDisplay() {
    return display;
}

public void setDisplay(boolean display) {
    this.display = display;
}

}

For each entry in your result-set create a new Question-object and add it to your question-list.

2.) You can't use the =?-syntax with a plain jdbc-Statement-object. You will have to use PreparedStatement for this, then you can set your query-parameters via the setXXX()-methods:

PreparedStatement stmt = conn.prepareStatement("update question set display='0' where id=?");
stmt.setInt(1, question.getId());
stmt.executeUpdate();

3.) When multiple users access your application I'm pretty sure you will get in trouble keeping your "display-state" in the database. Instead use the display-property of the Question-object (see above).