JSP SQL更新查询 [英] Jsp sql update query

查看:69
本文介绍了JSP SQL更新查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<%
  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>
<%}%>

这是我的代码.我先显示一些问题,然后将它们随机排列并随机选择5个问题.随机选择的5个问题需要显示为"0",如注释2所示.我做到了.我需要将str的id传递给数据库.有人可以帮忙吗?

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.)选择问题时,您不仅应该记住"问题文本,还应该记住" ID.为什么不创建一个新的问题"类,该类既可以保留值,又可以保留更多信息(正确答案等).

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;
}

}

为结果集中的每个条目创建一个新的Question对象,并将其添加到您的问题列表中.

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

2.)您不能将=?语法与普通的jdbc-Statement-object一起使用.为此,您将必须使用PreparedStatement,然后可以通过setXXX() -methods设置查询参数:

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.)当多个用户访问您的应用程序时,我很确定您将在数据库中保持显示状态"会遇到麻烦.而是使用问题"对象的显示属性(请参见上文).

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).

这篇关于JSP SQL更新查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆