copy command with psycopg2 library

前端 未结 3 1613
深忆病人
深忆病人 2021-01-04 11:21

Is it possible to run the command below through psycopg2? If so, how can I do it?

COPY table_name(col1,col2) FROM \'path/to/file.csv\' WITH HEADER DELIMITER          


        
3条回答
  •  [愿得一人]
    2021-01-04 11:41

    Yes!

    You can use the copy_from method:

    import psycopg2
    dbname=...
    user=...
    password=...
    host=...
    port=...
    con = psycopg2.connect(database=dbname,user=user,password=password,host=host,port=port)
    cur = con.cursor()    
    f = open('path/to/file.csv')
    cur.copy_from(f, 'test', columns=('col1', 'col2'), sep=",")
    con.commit()
    con.close()
    

提交回复
热议问题