63
loading...
This website collects cookies to deliver better user experience
$ pip install psycopg2
import psycopg2.sql as psql
import psycopg2.extras
import psycopg2
import csv
psycopg2.sql
contains SQL related helpers for generating SQL queries using python, and psycopg2.extras
contains the most important method of this tutorial - execute_values() - which we will use to finally execute the import query.DB = psycopg2.connect(
dsn=None,
dbname='your_database',
user='postgres',
host='localhost',
password='password'
)
db_cursor = DB.cursor
with open('your_csv_file.csv') as f:
reader = csv.reader(f, delimiter=',')
allrows = []
for line in reader:
allrows.append({ "column1": line[0], "column2": line[1] })
line
in the for loop is a list of all the values in the csv row currently being looped through. line[0]
would be the first field, line[1]
the second, and so on.line
/row in the csv that is looped over, we create a dictionary (map) where the keys are the field/column names and the values are... the values. allrows
variable will store a list of all the created dictionaries (each representing a row which we will insert).def create_sql(table_name, column_names):
query = psql.SQL("INSERT INTO {} ({}) VALUES %s").format(
psql.Identifier(table_name),
psql.SQL(', ').join(map(psql.Identifier, column_names))
)
query2 = psql.SQL("({})").format(
psql.SQL(', ').join(map(psql.Placeholder, column_names)),
)
return query.as_string(DB), query2.as_string(DB)
query2
represents a portion of the dynamically generated SQL - specifically the part that comes after VALUES
in a typical insert SQL query.insert_sql, template_sql = create_sql('your_table', ['column1', 'column2'])
allrows
, insert_sql
and template_sql
to see how my dummy data will get inserted: psycopg2.extras.execute_values(db_cusror, insert_sql, allrows, template_sql)
DB.commit()