Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a List/Set/Array to Apache QueryRunner as parameter value?

Tags:

java

jdbc

Is there any way to perform the following query:

select * from table where field in (?)

and pass a list/set/array as a value for ? placeholder.

I'm using QueryRunner from the Apache db-commons library.

like image 439
Kerb Avatar asked Sep 26 '13 16:09

Kerb


People also ask

How to represent array in query parameters?

Arrays in query parameters are sometimes represented by repeating a parameter multiple times:?foo=bar&foo=qux. Sometimes by repeating a parameter along with empty square brackets:

How to send array or list through a parameter in SQL Server?

In the latest versions of SQL Server, we can use the User Defined Data Type (UDT) with a base type of table to send array or list through a parameter. Let’s see with an example how to use User Defined Type to pass a list or an array to a stored procedure.

How to generate a URL-encoded querystring from an array in PHP?

You can use http_build_query to generate a URL-encoded querystring from an array in PHP. Whilst the resulting querystring will be expanded, you can decide on a unique separator you want as a parameter to the http_build_query method, so when it comes to decoding, you can check what separator was used.

How to pass array or list to stored procedure in SQL Server?

While using older versions of SQL Server, I’ve used to the XML method to pass array or list to stored procedure. In the latest versions of SQL Server, we can use the User Defined Data Type (UDT) with a base type of table to send array or list through a parameter.


1 Answers

Sure there is, use createArrayOf:

final List<Integer> id = new ArrayList<>();
id.add(12);
id.add(15);

final Array toDelete = connection.createArrayOf("int", id.toArray());

queryRunner.query(
    connection,
    "SELECT * FROM table WHERE id = ANY(?)",
    resultSetHandler,
    toDelete
);

(example is using PostgreSQL but should also work for others)

like image 118
rve Avatar answered Nov 03 '22 22:11

rve