【问题标题】:psycopg2: (col1, col2) IN my_list: ProgrammingError: syntax error at or near "ARRAY"psycopg2: (col1, col2) IN my_list: ProgrammingError: 在“ARRAY”处或附近出现语法错误
【发布时间】:2015-10-29 09:42:26
【问题描述】:

我想通过 psyopg2 执行这条 sql:

select indexname from pg_indexes where (tablename, indexname) in ( 
      ('tab1', 'index1'),
      ('tab2', 'index2') 
);

代码如下:

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

我得到了这个例外:

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

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

【问题讨论】:

    标签: sql postgresql psycopg2


    【解决方案1】:

    如果你传递一个元组而不是一个列表,它会起作用:

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

    如果你通过一个列表,不要问我为什么它会失败。

    【讨论】:

    • 如您在错误消息中看到的,Psycopg 将 Python 列表改编为 Postgresql 数组。一个元组适应一个记录。
    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 2018-03-12
    • 2021-12-13
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多