2

可能重复:
PreparedStatement IN 子句替代方案?

我想根据复选框选择从 MYSQL 中进行选择。(复选框有 ID,从数据库中选择应该选择 where ID= ? -> 选择的 ID)

我用 MVC 架构组织它:

  • 在 jsp 中是我的表单(它是动态的,所以可以有更多)

      <input type="checkbox" name="checkboxes" value="1">XY
      <input type="checkbox" name="checkboxes" value="2">XY
      <input type="checkbox" name="checkboxes" value="3">XY
    
  • 在servlet中我得到了值

      String[] catids  = request.getParameterValues("checkboxes");
    
      //Forward to bean -> doesnt work because catids is like an array
      FrageBean f=FragenBean.getRandomQuestionByCategory(catids);
    
  • 我的豆是:

    public static FrageBean getRandomQuestionByCategory(String catids) {
    ArrayList<Integer> alleFragenIds = new ArrayList<Integer>();
    
    DatabaseMetaData dbmd;
    Statement sql;
    Connection db = null;
    
    
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        System.out.println("driver not found");
    }
    try {
        db = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/xyz?"
                + "user=root&password=xyz");
        dbmd = db.getMetaData();
    
        System.out.println("Connected with: " + dbmd.getUserName() + " | "
                + "Connection to: " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion() + " successful.\n");
        sql = db.createStatement();
    } catch (SQLException ex) {
        System.out.println("Error: " + ex);
    }
    
    try {
    
        String query = "select id from quest where quest_id=?";
        PreparedStatement prest = db.prepareStatement( query);
    
        prest.setString(1, catids);
    
    
        ResultSet rs = prest.executeQuery();
        ArrayList fragenliste = new ArrayList();
        while (rs.next()) {
            int fragenid = rs.getInt("id");
            alleFragenIds.add(fragenid);
    
        }
    
        rs.close();
        db.close();
    
    
    } catch (SQLException ex) {
        System.out.println("Error: " + ex);
    }
    
    Random r = new Random();
    int frageIndex = r.nextInt(alleFragenIds.size());
     System.out.println("Contents of al: " + alleFragenIds);
    return new FrageBean(alleFragenIds.get(frageIndex));
    
    }
    

目前它只适用于一个 id(因为我只有一个选择)。我怎样才能用复选框做到这一点?如何将“catids”转发到 bean 并创建 mysql-query 动态?(从 fragen 中选择 id,其中 kategorie_id= [ALL CHECKED BOXES])

提前致谢!!!!

4

2 回答 2

2

在您的课程中创建以下方法。放置正确的驱动程序类和 url 连接并将 catids 作为字符串数组传递。

假设:我假设列“quest_id”是表quest中的int类型。

 public  void displayRecords(String[] catids)
{
    try
    {

        String queryStart = "select id from quest where quest_id in ( ";
        String queryMiddle = "";
        String prefix = "";
        String queryEnd = " )";
        String query = "";

        if (catids != null && catids.length > 0)
        {
            for (String id : catids)
            {
                queryMiddle = queryMiddle + prefix + id;
                prefix = ",";
            }

            query = queryStart + queryMiddle + queryEnd;
            System.out.println(query);

            Class.forName("DriverClass....................");
            Connection conn = DriverManager.getConnection("connection url ..................");
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            while (rs.next())
            {
                int fragenid = rs.getInt("id");
                System.out.println("ID = " + fragenid);
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
于 2012-12-13T12:18:15.930 回答
1

@RaisAlam 的答案很危险,因为它容易受到 SQL 注入的影响。这是一个固定版本:

public  void displayRecords(String[] catids) {
    try {
        String queryStart = "select id from quest where quest_id in ( ";
        String queryMiddle = "";
        String prefix = "";
        String queryEnd = " )";
        String query = "";

        if (catids != null && catids.length > 0) {
            for (String id : catids) {
                queryMiddle = queryMiddle + prefix + "?";
                prefix = ",";
            }
            query = queryStart + queryMiddle + queryEnd;
            System.out.println(query);
            Class.forName(....);
            Connection conn = DriverManager.getConnection(....);
            PreparedStatement stmt = conn.createPreparedStatement(query);
            int i = 1;
            for (String id : catids) {
                stmt.setInt(i++, Integer.parseInt(id));
            }
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                int fragenid = rs.getInt("id");
                System.out.println("ID = " + fragenid);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

为每个参数使用带有占位符的 PreparedStatement 是避免 SQL 注入的“最佳实践”方法。

于 2012-12-13T12:57:37.057 回答