How to use IN clause with PreparedStatement in PostgreSQL

爱⌒轻易说出口 提交于 2019-12-18 06:45:24

问题


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?


回答1:


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)




回答2:


Like this:

DELETE FROM employee WHERE ename = ANY(?)

The parameter should be formatted as an array literal, e.g. "{abc,bcd,efg}".




回答3:


You might want to try the below:

DELETE FROM employee 
 WHERE ename IN ('abc', 'bcd', 'efg')


来源:https://stackoverflow.com/questions/36929116/how-to-use-in-clause-with-preparedstatement-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!