简体   繁体   English

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

[英]Psycopg2 Insert on conflict with update Using Dictionary Values

I have some large datasets to perform the Postgres upsert function.我有一些大型数据集来执行 Postgres upsert function。 I am trying to sort out how to dynamically create the columns/values off my dictionary.我正在尝试弄清楚如何从我的字典中动态创建列/值。 I am able to insert using the As Is extension using:我可以使用 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),))

This seems to work fine if I am not doing any sort of conflict resolution.如果我不进行任何类型的冲突解决,这似乎工作正常。 or saying ON CONFLICT ( col1) DO NOTHING.或说 ON CONFLICT ( col1) DO NOTHING。 But I need to do an UPDATE of the values.但我需要对值进行更新。

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

So I am not sure if there is a good method to created that SET col1=val1 type set other than manually creating %(col1)s = %(val1)s variables in the SQL.所以我不确定除了在 SQL 中手动创建 %(col1)s = %(val1)s 变量之外,是否有一个好的方法来创建 SET col1=val1 类型集。

Using tools from here:从这里使用工具:

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

An example of something I do:我做的一个例子:

# 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)

Uses the dynamic capabilities of the sql module to build a query.使用sql模块的动态功能来构建查询。 The ex_list is just a list of 'excluded' strings equal in number to the number of the fields that are joined with field names later to create excluded.field_name . ex_list只是一个“ excluded.field_name ”字符串列表,其数量等于稍后与字段名称连接以创建 exclude.field_name 的字段数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM