How to use a list as a parameter source for SQL queries with Vertx JDBC Client?

六月ゝ 毕业季﹏ 提交于 2020-12-12 06:41:08

问题


I have a Vert.x web application that needs to query an AWS RDS instance running Postgres 10.7. The Vert.x JDBC client is io.vertx:vertx-jdbc-client:3.8.4. I want to query a table with the constraint that a certain column's value is included in a set of values:

select from table where column in/any (?)

I followed the Vertx documentation, which says to create a JsonArray and populate it with the values to inject into the query. The column is of type text and the list that I want to match on is a Java ArrayList<String>. My query code looks like:

String sql = "SELECT a FROM table WHERE col IN (?)";
List<String> values = someObject.someField();

            sqlClient.getConnection(connectionResult -> {
                if (connectionResult.failed()) {
                    // handle
                } else {
                    SQLConnection connection = connectionResult.result();

                    JsonArray params = new JsonArray()
                            .add(values);
                    connection.queryWithParams(sql, params, queryResult -> {
                       if (queryResult.failed()) {
                           // handle
                       } else {
                           // parse
                       }
                    });
                }
            });

The query fails with the error: org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of io.vertx.core.json.JsonArray. Use setObject() with an explicit Types value to specify the type to use.

I know that in the worst case, I can create a literal SQL string where col in (?, ?, ?, ..., ?) and add each String from the list to a JsonArray, but there must be a way to just add the ArrayList<String> as a parameter and keep the query simple. How can I specify a list of values to match against in my query?


回答1:


The Vert.x JDBC Client does not support array parameters in queries.

However it is possible with the Vert.x Pg Client, which does not depend on JDBC. You need to modify your query first:

SELECT a FROM table WHERE col = ANY(?)

Then:

pgClient.preparedQuery(query, Tuple.of(possibleValues), collector, handler);


来源:https://stackoverflow.com/questions/59758155/how-to-use-a-list-as-a-parameter-source-for-sql-queries-with-vertx-jdbc-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!