Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert ignore pandas dataframe into mysql

I want to "insert ignore" an entire pandas dataframe into mysql. Is there a way to do this without looping over the rows?

In dataframe.to_sql I only see the option if_exists 'append' but will this still continue on duplicate unique keys?

like image 225
user3605780 Avatar asked Jun 03 '15 22:06

user3605780


People also ask

How do I write pandas DataFrame in MySQL?

Create a dataframe by calling the pandas dataframe constructor and passing the python dict object as data. Invoke to_sql() method on the pandas dataframe instance and specify the table name and database connection. This creates a table in MySQL database server and populates it with the data from the pandas dataframe.


1 Answers

Consider using a temp table (with exact structure of final table) that is always replaced by pandas then run the INSERT IGNORE in a cursor call:

dataframe.to_sql('myTempTable', con, if_exists ='replace')

cur = con.cursor()
cur.execute("INSERT IGNORE INTO myFinalTable SELECT * FROM myTempTable")
con.commit()
like image 53
Parfait Avatar answered Sep 20 '22 18:09

Parfait