Python psycopg2 如何在 uuid 数组条件下查询

How Python psycopg2 query in condition with uuid array

给定一个table

create table test_db (
  id uuid
)

在 Python 中使用库 psycopg2,我们可以进行查询

cursor.execute("select * from test_db where id in" +
   " ('5ed11bbf-ffd1-4124-ba3d-5e392dc9db96','14acfb5b-3b09-4728-b3b3-8cd484b310db')")

但是如果我参数化id,改为

cursor.execute("select * from testdb where id in (%s)",
   ("'5ed11bbf-ffd1-4124-ba3d-5e392dc9db96','14acfb5b-3b09-4728-b3b3-8cd484b310db'",))

它不起作用,说

psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type uuid: "'5ed11bbf-ffd1-4124-ba3d-5e392dc9db96','14acfb5b-3b09-4728-b3b3-8cd484b310db'"

如何将 in (%s) 与 uuid 数组一起使用?

每个值一个 %s。

cursor.execute(
   "select * from testdb where id in (%s, %s)",
   ('5ed11bbf-ffd1-4124-ba3d-5e392dc9db96','14acfb5b-3b09-4728-b3b3-8cd484b310db')
)

你有多余的引号,所以你只传递了一个字符串参数。

您可以使用元组并使用 IN,但使用列表和 any() 是更好的选择,因为它不会在您传递空列表时立即在您的脸上爆炸。

cursor.execute("select * from testdb where id = any(%s)",
   ([UUID('5ed11bbf-ffd1-4124-ba3d-5e392dc9db96'), UUID('14acfb5b-3b09-4728-b3b3-8cd484b310db')],))

它可能在不使用 UUID 的情况下工作,但你只是这样混淆了类型系统。

感谢@piro的回答,经过多次尝试,得到了有效代码

cursor.execute("select * from testdb where id = any(%s::uuid)",
   (['5ed11bbf-ffd1-4124-ba3d-5e392dc9db96',
     '14acfb5b-3b09-4728-b3b3-8cd484b310db'],))

id = any(%s::uuid)不能用id in (%s::uuid)代替。