简体   繁体   English

如何将Arraylist的每个元素用作SQL语句中的列值(为每个元素重复Arraylist)?

[英]How to use each element of Arraylist as a column value in SQL statement (iterate the Arraylist for each element)?

I collected the distinct Item value from the table in a ArrayList. 我从ArrayList的表中收集了不同的Item值。 Now I want to iterate each value of ArrayList as a column value. 现在,我想将ArrayList的每个值迭代为列值。

PreparedStatement pstmt =conn.preparedStatement("select distinct(A.ID) from Products A,Products B where A.ID=B.ID and A.Item in (?)");

The above must comes under the loop and each element in ArrayList is used as the column value for each iteration. 上面的内容必须在循环之下,并且ArrayList中的每个元素都用作每次迭代的列值。

You need to add a ? 您需要添加一个? parameter marker for each value, so your code would be something like this. 每个值的参数标记,因此您的代码将如下所示。

Connection conn = /*connection provided elsewhere*/;
List<String> items = /*item values provided elsewhere*/;

StringBuilder sql = new StringBuilder();
sql.append("select distinct A.ID" +
            " from Products A" +
            " join Products B on B.ID = A.ID" +
           " where A.Item in (");
for (int i = 0; i < items.size(); i++) {
    if (i != 0) sql.append(',');
    sql.append('?');
}
sql.append(')');
try (PreparedStatement stmt = conn.prepareStatement(sql.toString())) {
    for (int i = 1; i <= items.size(); i++)
        stmt.setString(i, items.get(i));
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            int id = rs.getInt("ID");
            // use id here
        }
    }
}

In Java 8, using a StringJoiner can simplify the code a bit. 在Java 8中,使用StringJoiner可以稍微简化代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM