Shivam
Shivam

Reputation: 243

How to insert dataframe into mysql table in python?

I am trying to run python script to insert values in mysql table from a dataframe. But the problem is dataframe columns are not the same with mysql table. I need someone help to insert data.

Example: MySql Table temp:

create table temp ( Table_name varchar(255),
                    Data_set_name varchar(255),
                    Current_Count int,
                    Load_date varchar(255), 
                    Recon_Date varchar(255)
);

Dataframe df:

Master Job Name|Current_Count|Start_time
GRP|32452|04-24-2020 02:14:22
PCYC_VOC_Data_load|24|04-23-2020 09:31:10
IM_XREF_BRIDGE_PROD|3039|04-24-2020 02:04:32

Expected result in MySql table temp:

Table_name           Data_set_name    Current_Count   Load_date             Recon_Date
GRP                  Refined          32452           04-24-2020 02:14:22
PCYC_VOC_Data_load   Refined          24              04-23-2020 09:31:10
IM_XREF_BRIDGE_PROD  Refined          3039            04-24-2020 02:04:32

Please let me know if you required any information.

Upvotes: 1

Views: 621

Answers (1)

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

df.to_sql(con=con, name='table_name_for_df', if_exists='replace', flavor='mysql')

connection with MySQLdb

from pandas.io import sql
import MySQLdb

con = MySQLdb.connect() 

sql.write_frame(df, con=con, name='table_name_for_df', 
                if_exists='replace', flavor='mysql')

use If table exists carefully as if you say replace it will: drop it, recreate it, and insert data.

You can try: append: If table exists, insert data. Create if does not exist.


Once you are done with this you will have SQL table with df data. You can change/add columns/column names later

Upvotes: 1

Related Questions