Created
August 7, 2018 09:10
-
-
Save elena-roff/cfa0d80789ffa232bfa4752581d68b58 to your computer and use it in GitHub Desktop.
Write to MySQL DB from csv file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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