PostgreSQL:如何在 PreparedStatement 中创建带有空字符串的数组?

PostgreSQL: How to create array with empty string in PreparedStatement?

我有一个空名称值的测试 table:

create table tmp_table_test (id serial, name varchar(100));

insert into tmp_table_test (name) values ('');
insert into tmp_table_test (name) values ('a');
insert into tmp_table_test (name) values ('b');

当我运行这个查询时:

SelectSQLPrepared("SELECT id, name FROM tmp_table_test WHERE name IN ('', 'a') order by 1;")

我看到两条记录。

现在我想把它改成 PreparedStatement 并看到相同的记录,但我不知道如何将空字符串插入数组。

我试过了

SelectSQLPrepared("SELECT id, name FROM tmp_table_test WHERE name IN (SELECT unnest(?::text[])) order by 1;", "{'', a}")

或:

SelectSQLPrepared("SELECT id, name FROM tmp_table_test WHERE name = ANY (?::text[])", "{'', a}")

但它只返回名称为 a 的记录。

我试过了:

SelectSQLPrepared("SELECT id, name FROM tmp_table_test WHERE name IN (SELECT unnest(?::text[])) order by 1;", "{, a}")

但它给出了错误:

ERROR: malformed array literal: "{, a}"

我发明的唯一查询看起来很奇怪:

SelectSQLPrepared("SELECT id, name FROM tmp_table_test WHERE name IN (SELECT unnest(string_to_array(?, ','))) order by 1;", ",a")

,a作为string_to_array()的参数,它给我一个空字符串数组和a,但我不知道如何转义可以在输入中的冒号值。

是否有任何解决方案可以使用带有 IN 子句的准备语句来搜索空字符串值?

有数组构造函数ARRAY

postgres=# SELECT ARRAY[''];
┌───────┐
│ array │
╞═══════╡
│ {""}  │
└───────┘
(1 row)

postgres=# SELECT ARRAY['', 'a'];
┌────────┐
│ array  │
╞════════╡
│ {"",a} │
└────────┘
(1 row)

您可以使用 ANY 运算符直接传递数组(无论如何 IN 都会被重写)并将其转换为准备好的语句源:

SELECT id, name FROM tmp_table_test WHERE name = any(cast ? as text[]) order by 1

传递一个像 {"", a} 这样的字符串文字,例如:

pstmt.setString(1, "{\"\", a}"