I have a script that downloads data from an API and turns all of this info into a CSV. I need this data to be into a table in MySQL (I already created it and established the connection with MySQL Connector). Is there anyway to do this?
-
Possible duplicate of How can I insert data into a MySQL database?dot.Py– dot.Py2017-02-21 14:52:11 +00:00Commented Feb 21, 2017 at 14:52
-
1Any error message? Please be more specific about your problem.dot.Py– dot.Py2017-02-21 14:53:33 +00:00Commented Feb 21, 2017 at 14:53
-
too wise, please be more precise. importing csv data into MySql is something very well documentedkaz– kaz2017-02-21 15:25:07 +00:00Commented Feb 21, 2017 at 15:25
Add a comment
|
1 Answer
Pandas.DataFrame has a method to_sql which writes a dataframe into a sql table.
Simplest way to use the method is to create a connection with sqlalchemy.(You will need to install mysql-python) and use .to_sql to read the data into the table.
from sqlalchemy import create_engine
engine = create_engine('mysql://username:password@host:port/database') #change to connect your mysql
#if you want to append the data to an existing table
df.to_sql(name='SQL Table name',con=engine,if_exists='append',index=False)
#if you want to create a new table
df.to_sql(name='New SQL Table name',con=engine,if_exists='fail',index=False)
Please note that you will need to use param dtype to define the dtype of the table columns if you have created the table before hand.
1 Comment
Alex Fung
@PaulaC, Glad I can help. Be sure to accept my answer.