psycopg2:(col1,col2)IN my_list:ProgrammingError:"ARRAY"或附近的语法错误

gue*_*tli 12 sql postgresql psycopg2

我想通过psyopg2执行这个sql:

select indexname from pg_indexes where (tablename, indexname) in ( 
      ('tab1', 'index1'),
      ('tab2', 'index2') 
);
Run Code Online (Sandbox Code Playgroud)

这是代码:

cursor.execute(
'select tablename, indexname from pg_indexes where (tablename, indexname) IN %s;', [
    [('tab1', 'col1'), ('tab2', 'col2')],
               ])
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

ProgrammingError: syntax error at or near "ARRAY"
LINE 1: ...e from pg_indexes where (tablename, indexname) IN ARRAY[('ta...
Run Code Online (Sandbox Code Playgroud)

如何将元组列表传递给PostgreSQL和psyopg2?

gue*_*tli 12

如果你传递一个元组而不是一个列表,它可以工作:

cursor.execute(
'select tablename, indexname from pg_indexes where (tablename, indexname) IN %s;', [
    tuple([('tab1', 'col1'), ('tab2', 'col2')]),
               ])
Run Code Online (Sandbox Code Playgroud)

如果你通过一个清单,不要问我失败的原因.

  • 正如您在错误消息中看到的那样,Psycopg 将 Python 列表改编为 Postgresql 数组。元组适应记录。 (2认同)