Skip to content

Instantly share code, notes, and snippets.

@encryptblockr
Forked from amulya349/copy_csv_to_db.py
Created May 20, 2021 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save encryptblockr/738c528753c95189361ec534c0bdb903 to your computer and use it in GitHub Desktop.
Save encryptblockr/738c528753c95189361ec534c0bdb903 to your computer and use it in GitHub Desktop.
This script can be used to copy a CSV file (with header) to a Postgres remote database.
#!/usr/bin/env/python
import psycopg2
# Get a database connection
dsn = "dbname=%s user=%s password=%s host=%s port=%s" % ('db_name','username','password','remote_host_ip','port')
conn = psycopg2.connect(dsn)
query = "COPY public.hiringpattern_new FROM stdin WITH CSV HEADER DELIMITER as ',' "
fp = open('csv_file_path', 'r')
cur = conn.cursor()
cur.copy_expert(sql=query, file=fp)
conn.commit()
cur.close()
fp.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment