Psycopg2 插入冲突与更新使用字典值

Psycopg2 Insert on conflict with update Using Dictionary Values

我有一些大型数据集来执行 Postgres 更新插入功能。我正在尝试弄清楚如何从我的字典中动态创建 columns/values 。我可以使用 As Is 扩展名插入:

sql = "INSERT INTO table (%s) VALUES %s;"
cols = mydict.keys()
vals = [mydict[col] for col in cols]
cursor.execute(sql, (AsIs(', '.join(cols)), tuple(vals),))

如果我不做任何类型的冲突解决,这似乎工作正常。或者说 ON CONFLICT ( col1) DO NOTHING。但是我需要更新这些值。

sql = "INSERT INTO table (%s) VALUES %s ON CONFLICT (col1) DO UPDATE SET ....???"

所以我不确定是否有创建 SET col1=val1 类型集的好方法,而不是在 SQL 中手动创建 %(col1)s = %(val1)s 变量。

使用此处的工具:

https://www.psycopg.org/docs/sql.html

我做的一个例子:

# div_flds is list of field names
ex_list = ["excluded" for i in range(len(div_flds))]
div_insert_sql = sql.SQL("""INSERT INTO
                stock_div({})
            VALUES
                ({})
            ON CONFLICT
                (sd_line_id)
            DO UPDATE
                SET
                    ({}) = ({})
            RETURNING
                sd_line_id
            """).format(sql.SQL(", ").join(map(sql.Identifier, div_flds)),
                        sql.SQL(", ").join(map(sql.Placeholder, div_flds)),
                        sql.SQL(", ").join(map(sql.Identifier, div_flds)),
                        sql.SQL(", ").join(map(sql.Identifier, ex_list,
                                               div_flds))
                        )
cur.execute(div_insert_sql, div_data)

使用 sql 模块的动态功能构建查询。 ex_list 只是一个 'excluded' 字符串列表,其数量等于稍后与字段名称连接以创建 excluded.field_name.

的字段数量