pandas DataFrame to_sql Python

As I looked into other topics I found out that a solution like this one from James at questions about pandas.to_sql could be the solution for your problem. Here is what he said.

Your way is not supported anymore. Try this?

from sqlalchemy import create_engine
import pandas as pd


engine = create_engine("mysql://root:matt123@localhost/ada")
df=pd.DataFrame(['A','B'],columns=['new_tablecol'])
df.to_sql(name='new_table',con=engine,if_exists='append')

Syntax is:

engine = create_engine("mysql://USER:PASSWORD@HOST/DATABASE")

I'm not sure if the use of pysql is a necessity, but in the event sqlite3 will suffice, then it could look like this:

import pandas
import sqlite3 as db

DB = db.connect('DB.db')
csv1 = pandas.read_csv('C:\\…..csv')
csv1.to_sql(name='Orders', con=DB, if_exists='replace')
#replace is one of three options available for the if_exists parameter
DB.close()

However, this format and method are probably unrelated to the error you received, which may have had something to do with the data within your csv file. Without seeing it, it's hard to be certain.

Tags:

Python

Mysql