copy data from csv to postgresql using python

前端 未结 8 1177
遥遥无期
遥遥无期 2021-02-04 03:32

I am on windows 7 64 bit. I have a csv file \'data.csv\'. I want to import data to a postgresql table \'temp_unicommerce_status\' via a python script.

My Script is:

8条回答
  •  孤独总比滥情好
    2021-02-04 03:56

    The way I solved this problem particular to use psychopg2 cursor class function copy_expert (Docs: http://initd.org/psycopg/docs/cursor.html). copy_expert allows you to use STDIN therefore bypassing the need to issue a superuser privilege for the postgres user. Your access to the file then depends on the client (linux/windows/mac) user's access to the file

    From Postgres COPY Docs (https://www.postgresql.org/docs/current/static/sql-copy.html):

    Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.

    You can also leave the permissions set strictly for access to the development_user home folder and the App folder.

    csv_file_name = '/home/user/some_file.csv'
    sql = "COPY table_name FROM STDIN DELIMITER '|' CSV HEADER"
    cursor.copy_expert(sql, open(csv_file_name, "r"))
    

提交回复
热议问题