PreparedStatement IN clause alternatives?

前端 未结 30 3885
情歌与酒
情歌与酒 2020-11-21 05:19

What are the best workarounds for using a SQL IN clause with instances of java.sql.PreparedStatement, which is not supported for multiple values du

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 05:39

    You can use Collections.nCopies to generate a collection of placeholders and join them using String.join:

    List params = getParams();
    String placeHolders = String.join(",", Collections.nCopies(params.size(), "?"));
    String sql = "select * from your_table where some_column in (" + placeHolders + ")";
    try (   Connection connection = getConnection();
            PreparedStatement ps = connection.prepareStatement(sql)) {
        int i = 1;
        for (String param : params) {
            ps.setString(i++, param);
        }
        /*
         * Execute query/do stuff
         */
    }
    

提交回复
热议问题