Search code examples
pythonpostgresqlcsvstdinpsycopg2

How Postgresql COPY TO STDIN With CSV do on conflic do update?


I want to do

 " on conflict (time) do update set name , description "

but I have no idea when I use stdin with csv , I don't know what name equal what? and description equal what...

table_a:

enter image description here

xxx.csv:

enter image description here

with open('xxx/xxx.csv', 'r', encoding='utf8') as f:
    sql = """
    COPY table_a FROM STDIN With CSV on conflict (time) 
    do update set name=??, description=??;
    """
    cur.copy_expert(sql, f)
    conn.commit()

Solution

  • Thanks for every master's solution.

    this is my solution.

    sql = """
    CREATE TABLE temp_h (
        time ,
        name,
        description
    );
    COPY temp_h FROM STDIN With CSV;
    
    INSERT INTO table_a(time, name, description)
    SELECT *
    FROM temp_h ON conflict (time) 
    DO update set name=EXCLUDED.name, description=EXCLUDED.description;
    
    DROP TABLE temp_h;
    """