【问题标题】:update the table based on primary key for postgres in python基于python中postgres的主键更新表
【发布时间】:2019-12-13 00:23:13
【问题描述】:

我有大约 1000 个不同的文件,我正在使用 python 将它们加载到 postgres 数据库中。我能够将 csv 文件插入表中,但如果记录已经加载到表中,它应该根据主键使用新值更新表,如果表中不存在主键,则应该插入。这意味着我需要根据主键更新插入(不指定主键的列名)

我尝试过的代码将 csv 插入到表格中。

import csv
import psycopg2
conn = psycopg2.connect(user = "postgres",
                             password = "12345",
                              host = "127.0.0.1",
                              port = "5432",
                              database = "trial")
cur = conn.cursor()
f = open('/home/Documents/try.csv')
next(f)
cur.copy_from(f,'users1', sep=',', null='')
conn.commit()

csv文件如下 id 是主键(更新时不应该取列名)

第一个 csv 插入到表中

id name
1  A
2  B

第二个 csv

id name
1  C
3  O
4  P

最终更新和插入的表应该是

id name
1   C
2   B
3   O
4   P

由于 id 为 1 的第二个 csv 文件的名称为 C,因此必须更新表。

【问题讨论】:

    标签: python-3.x postgresql insert python-3.5 psycopg2


    【解决方案1】:

    试试这个..

    create table t1 (id integer,name character varying)
    
    insert into t1
    select 1,'A'
    union all
    select 2,'B'
    
    
    create table t2 (id integer,name character varying)
    
    insert into t2
    select 1,'C'
    union all
    select 3,'O'
    union all
    select 4,'P'
    
    SELECT * FROM t1
    SELECT * FROM t2
    
    select coalesce(t1.id,t2.id),case when t2.name is not null then t2.name else t1.name end as name
    from t1
    full join t2 on t2.id = t1.id
    

    结果:

    1;"C"
    2;"B"
    3;"O"
    4;"P"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2011-03-16
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 2017-08-23
      相关资源
      最近更新 更多