小编Dob*_*bob的帖子

PostgreSQL/Psycopg2 upsert 语法更新列

当出现 id 冲突时,我想让 Psycopg2 更新col1col2col3

在我的 Python 代码中,我目前的插入 SQL 为:

insert_sql = '''INSERT INTO {t} (id,col1,col2,col3)
        VALUES (%s,%s,NULLIF(%s, 'nan'), NULLIF(%s, 'nan'))
        ON CONFLICT (id)
        DO NOTHING;'''
Run Code Online (Sandbox Code Playgroud)

基本上我想设置而不是什么都不做:

(col1,col2,col3) = (%s,NULLIF(%s, 'nan'), NULLIF(%s, 'nan'))

忽略插入 ID 并更新 col1、col2 和 col3。问题是%s使用 Psycopg2 在 Python 中传递元组变量:

cur.execute(insert_sql.format(t='my_table'),(int(id),new_col1,new_col2,new_col3))
Run Code Online (Sandbox Code Playgroud)

用于引用%s对应于 col1、col2 和 col3 以更新 ON CONFLICT的语法是什么?

postgresql insert python upsert

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

insert ×1

postgresql ×1

python ×1

upsert ×1