Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use IN clause with PreparedStatement in PostgreSQL

I have to write a SQL query for Postgres database as follows:

DELETE FROM employee WHERE ename IN (?)

I want to pass ename as list or string which will contain multiple employee names, e.g. "abc, bcd, efg". How to set the values?

How to use IN clause with PreparedStatement in Postgres?

like image 425
Ritesh Avatar asked Apr 29 '16 03:04

Ritesh


People also ask

Can we use with clause in PostgreSQL?

You can use data-modifying statements (INSERT, UPDATE or DELETE) in WITH. This allows you to perform several different operations in the same query.

How do you pass parameters in PreparedStatement?

To execute a statement with Where clause using PreparedStatement. Prepare the query by replacing the value in the clause with place holder “?” and, pass this query as a parameter to the prepareStatement() method.

What method on a PreparedStatement can you use to execute a select query?

As with Statement objects, to execute a PreparedStatement object, call an execute statement: executeQuery if the query returns only one ResultSet (such as a SELECT SQL statement), executeUpdate if the query does not return a ResultSet (such as an UPDATE SQL statement), or execute if the query might return more than one ...


1 Answers

There are several ways to do this. The clean way is to pass an array to the prepared statement. An alternative to Nick's answer is to pass a proper java.sql.Array value:

PreparedStatement pstmt = connection.prepareStatement(
    "DELETE FROM employee WHERE ename = ANY (?)");
String[] idList = new String[] {"abc", "bcd", "efg"};
Array ids = connection.createArray("varchar", idList);
pstmt.setArray(1, ids);

Another option is to use Postgres' string functions to convert the comma separated list to an array. That is probably the easiest way:

PreparedStatement pstmt = connection.prepareStatement(
     "DELETE FROM employee WHERE ename = ANY (string_to_array(?, ','))");
psmt.setString(1, "abc,bcd,efg");

Note that you must not have spaces between the comma and the value! Those spaces will be part of the value that is stored in the array after string_to_array() has done it's job so comparison would e.g. be ename = ' bcd' which would fail if there is no leading space in the column ename(which is highly likely)

like image 173
a_horse_with_no_name Avatar answered Sep 21 '22 20:09

a_horse_with_no_name