2

Is there a way to pass an array of strings for a "WHERE country IN (...)" query?

something like this:

String[] countries = {"France", "Switzerland"};
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM table WHERE country IN (?...)");
pstmt.setStringArray(1, countries);
pstmt.executeQuery();

an ugly workaround would be to create the query based on the size of the array

String[] countries = {"France", "Switzerland"};
if (countries.size() == 0) { return null; }
String query = "SELECT * FROM table WHERE country IN (?";
for (int i = 1; i < countries.size; i++) { query += ", ?"; }
PreparedStatement pstmt = con.prepareStatement(query);
for (int i = 0; i < countries.size; i++) { pstmt.setString(1+i, countries[i]); }
pstmt.executeQuery();

but this looks really ugly.

any idea?

Filburt
  • 17,626
  • 12
  • 64
  • 115
David Portabella
  • 12,390
  • 27
  • 101
  • 182

4 Answers4

4

No, it's not possible. ORMs like Hibernate or wrapper APIs like Spring JDBC allows doing that. But with plain JDBC, you must do it yourself.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • That's not really true. Many databases support parametrized IN(...) conditions using PreparedStatements. – jarnbjo Jun 04 '12 at 09:25
  • @jambo: It has nothing to do with databases supporting them or not. All databases do, AFAIK. But you need one placeholder per element of the IN clause. – JB Nizet Jun 04 '12 at 10:01
  • 1
    No, that is exactly what you don't need. The exact syntax is DB specific, here for example a solution for Oracle: http://blogs.itemis.de/kloss/2009/03/05/arrays-preparedstatements-jdbc-and-oracle/ – jarnbjo Jun 04 '12 at 10:12
  • OK, so you don't need them if you create an additional type in your database, if you change your query, and if you use proprietary types. Point taken. But I would prefer generating the query by myself, keep my code database-agnostic, and my database setup simpler. – JB Nizet Jun 04 '12 at 10:20
0

I think the work around would be formulating the entire query string at runtime and using a Statement object instead of PreparedStatement.

Michael
  • 11
0

No way to try this.See here to other ways.But there is one exception, if you use oracle database then you can try this

Sai Ye Yan Naing Aye
  • 6,622
  • 12
  • 47
  • 65
0

If your database engine support IN (subquery), you can create a view or memory table to do it.

Yongxin Zhao
  • 124
  • 1