Skip to content

Instantly share code, notes, and snippets.

@elena-roff
Created August 7, 2018 09:10
Show Gist options
  • Save elena-roff/cfa0d80789ffa232bfa4752581d68b58 to your computer and use it in GitHub Desktop.
Save elena-roff/cfa0d80789ffa232bfa4752581d68b58 to your computer and use it in GitHub Desktop.
Write to MySQL DB from csv file
import pandas as pd
import mysql.connector.pooling
start_cred = {
'db_user': <db_user>,
...
}
cnx = mysql.connector.pooling.MySQLConnectionPool(**start_cred)
data = pd.read_csv('filename')
# query to fill in
QUERY = "insert_query.sql"
# Example:
# INSERT INTO table (id, item)
# VALUES (%(id)s, %(item)s);
with open(QUERY) as fh:
query = fh.read()
try:
con = cnx.get_connection()
cur = con.cursor()
for _, row in data.iterrows():
param = {
'id': row['id'],
'cluster' : row['item'],
}
cur.execute(query, param)
con.commit() # to apply changes
finally:
con.close()
cur.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment