【问题标题】:psycopg2 string composition errorpsycopg2 字符串组合错误
【发布时间】:2018-01-08 02:39:57
【问题描述】:

我正在做一个 upsert。

owner.sq_properties = ['name', 'place', 'email_address',                      'preferred_transport', 'note', 'address_line_one',                      'address_line_two', 'address_line_three', 'contact_one',                'contact_two', 'contact_three', 'gst_number', 'nickname']

声明:

sq = sql.SQL("insert into master.customer select * from public.customer on conflict (id) do update set({})=({})").format(sql.SQL(',').join(sql.Identifier(n) for n in owner.sq_properties),sql.SQL(',').join(sql.Identifier("excluded."+n) for n in owner.sq_properties))

当我执行时:

print(sq.as_string(cursor)) 

输出是:

insert into master.customer select * from public.customer on conflict (id) do update set ("name", "place", "email_address", "preferred_transport", "note", "address_line_one", "address_line_two", "address_line_three", "contact_one", "contact_two", "contact_three", "gst_number", "nickname") = ("excluded.name", "excluded.place", "excluded.email_address", "excluded.preferred_transport", "excluded.note", "excluded.address_line_one", "excluded.address_line_two", "excluded.address_line_three", "excluded.contact_one", "excluded.contact_two", "excluded.contact_three", "excluded.gst_number", "excluded.nickname")

错误:

cursor.execute(sq)
psycopg2.ProgrammingError: column "excluded.name" does not exist
LINE 1: ...o", "contact_three", "gst_number", "nickname") = ("excluded..

我做错了什么?

【问题讨论】:

    标签: psycopg2 psql


    【解决方案1】:

    想通了。 excluded. 应该是一个 sql 标识符。

    joined =sql.SQL(',').join(sql.SQL('excluded.')+sql.Identifier(n) for n in owner.sq_properties)
    

    更正声明:

    sql.SQL("insert into master.customer select * from public.customer on conflict (id) do update set ({}) = ({})      returning id").format(sql.SQL(',').join(sql.Identifier(n) for n in owner.sq_properties), joined)
    

    【讨论】:

      猜你喜欢
      • 2022-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多