【问题标题】:How to use each element of Arraylist as a column value in SQL statement (iterate the Arraylist for each element)?SQL语句中如何使用Arraylist的每个元素作为列值(为每个元素迭代Arraylist)?
【发布时间】:2015-09-08 01:18:46
【问题描述】:

我从 ArrayList 的表中收集了不同的 Item 值。现在我想将 ArrayList 的每个值迭代为列值。

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

以上必须在循环下,ArrayList中的每个元素都被用作每次迭代的列值。

【问题讨论】:

  • 你能更清楚一点吗 - 你从 ArrayList 中的 DB(使用你提到的查询)中获取了不同的值。正确的?现在您希望数组中的每个元素都用于其他查询吗?
  • 显示您尝试过的内容。
  • @SandeepJindal 你为什么要减少我的观点?
  • @SrividhyaShama 我没有。我相信 cmets 比 downvote 更有意义。

标签: java mysql arraylist prepared-statement


【解决方案1】:

您需要为每个值添加一个? 参数标记,因此您的代码将是这样的。

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

在 Java 8 中,使用 StringJoiner 可以稍微简化代码。

【讨论】:

  • 我将列表存储在“ArrayList 项目中,它显示在可压缩错误中。我如何将此代码用于字符串数组?
  • 你必须澄清你的意思。您的代码使用 Item 列上的 in 子句进行查询。现在你说你有一个数组列表?这甚至是如何开始融合在一起的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多