Vertx JDBC client queryWithParams - how to add a list?

前端 未结 2 1261
死守一世寂寞
死守一世寂寞 2021-01-22 14:14

I have SQL query with condition currency in ? and I\'m using vertx JDBC client queryWithparams method, which receives query parameters in JsonArray.

相关标签:
2条回答
  • 2021-01-22 14:49

    The short answer is that you can't add a List as a query parameter with the generic Vertx JDBC client, but since you're using Postgres there is a Postgres-specific library called vertx-pg-client that you can use. I implemented roughly the same query as you did with this code:

    List<String> currencies = whatever();
    String uri = "your-uri";
    String query = "select from table where currency = any($1)";
    PgConnection.connect(vertx, uri, connectionResult -> {
        if (connectionResult.failed()) {
            // handle
        } else {
            PgConnection connection = connectionResult.result();
            Tuple params = Tuple.of(currencies);
    
            doQuery(query, connection, params).setHandler(queryResult -> {
                connection.close();
                msg.reply(queryResult.result());
            });
        }
    });
    
        private Future<String> doQuery(String sql, PgConnection connection, Tuple params) {
            Promise<String> promise = Promise.promise();
            connection.preparedQuery(sql, params, res -> {
                if (res.failed()) {
                    // log
                    promise.fail(res.cause());
                } else {
                    RowSet<Row> rowSet = res.result();
                    // do something with the rows and construct a return object (here, a string)
                    String result = something;
                    promise.complete(result);
                }
            });
            return promise.future();
        }
    

    All credit goes to @tsegismont who helped me with the same question here.

    0 讨论(0)
  • 2021-01-22 14:53

    There are two options.

    If you want to support multiple databases, you'll have to expand your expression yourself:

    "... currency IN (" + String.join(",", Collections.nCopies(currencies.size(), "?")) + ")"
    

    If you support only PostreSQL, you can use ANY operator instead:

    WHERE currency = ANY(?)
    
    0 讨论(0)
提交回复
热议问题