Home >Database >Mysql Tutorial >How to Insert a Pandas DataFrame into a MySQL Database Using MySQLdb?
How can we directly insert an entire pandas dataframe into an existing MySQL database table using MySQLdb?
Using the write_frame method from the pandas.io.sql module, you can insert a dataframe into MySQL as follows:
sql.write_frame(df, con=con, name='table_name', if_exists='replace', flavor='mysql')
where:
if_exists specifies how to handle an existing table:
The preferred method for inserting dataframes into SQL databases is now to_sql:
df.to_sql(con=con, name='table_name', if_exists='replace', flavor='mysql')
Establish a connection to MySQL using MySQLdb:
from pandas.io import sql
import MySQLdb
con = MySQLdb.connect()
For a table with ID, data1, and data2 columns, the Python script to insert the corresponding dataframe would be:
import pandas as pd
import MySQLdb
df = pd.DataFrame({'ID': [1, 2, 3], 'data1': ['a', 'b', 'c'], 'data2': [10, 20, 30]})
con = MySQLdb.connect()
sql.write_frame(df, con=con, name='table_name', if_exists='replace', flavor='mysql')
The above is the detailed content of How to Insert a Pandas DataFrame into a MySQL Database Using MySQLdb?. For more information, please follow other related articles on the PHP Chinese website!