我有条件currency in ?
的SQL查询我正在使用 vertx JDBC 客户端queryWithparams
方法,该方法在 JsonArray 中接收查询参数。
如何将可能的currency
值列表传递给查询?我试过new JsonArray().add(new JsonArray(currencies)
但得到异常
org.postgresql.util.PSQLException:无法推断用于io.vertx.core.json.JsonArray实例的SQL类型。将 setObject(( 与显式 Types 值一起使用以指定要使用的类型。
简短的回答是,您不能使用通用的 Vertx JDBC 客户端将 List 添加为查询参数,但由于您使用的是 Postgres,因此您可以使用一个名为 vertx-pg-client 的特定于 Postgres 的库。我实现了与您使用此代码大致相同的查询:
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();
}
所有的功劳都归功于@tsegismont他在这里帮助我解决了同样的问题。
有两个选项。
如果要支持多个数据库,则必须自己扩展表达式:
"... currency IN (" + String.join(",", Collections.nCopies(currencies.size(), "?")) + ")"
如果您仅支持 PostreSQL,则可以改用ANY
运算符:
WHERE currency = ANY(?)