我需要为Postgres数据库编写以下SQL查询:
DELETE FROM employee WHERE ename IN (?)
我想将ename
作为包含多个员工名称的列表或字符串进行传递,例如"abc, bcd, efg"
。如何设置值?
在Postgres中如何使用PreparedStatement
和IN
子句?
我需要为Postgres数据库编写以下SQL查询:
DELETE FROM employee WHERE ename IN (?)
我想将ename
作为包含多个员工名称的列表或字符串进行传递,例如"abc, bcd, efg"
。如何设置值?
在Postgres中如何使用PreparedStatement
和IN
子句?
有几种方法可以做到这一点。最好的方法是向预处理语句传递一个数组。另一种替代Nick答案的方法是传递一个正确的java.sql.Array
值:
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);
另一个选择是使用Postgres的字符串函数将逗号分隔的列表转换为数组。这可能是最简单的方法:
PreparedStatement pstmt = connection.prepareStatement(
"DELETE FROM employee WHERE ename = ANY (string_to_array(?, ','))");
psmt.setString(1, "abc,bcd,efg");
string_to_array()
完成其工作后,这些空格将是存储在数组中的值的一部分,因此比较可能是ename = ' bcd'
,如果列ename
中没有前导空格(这是极有可能的),则会失败。connection.createArrayOf
而不是connection.createArray
(保持参数相同)。谢谢。 - AndresDELETE FROM employee
WHERE ename IN ('abc', 'bcd', 'efg')
where ename = any(<array parameter or constant here>)
。有趣的是,PostgreSQL会将in
子句内部转换为= any(...)
,可以在查询计划中看到这一点。 - Abelisto