Search code examples
pythonpandaspymysql

How insert the dataframe output to mysql


import pymysql
import pandas as pd
db = pymysql.connect('localhost', 'testuser', 'test123', 'world')
df1 = pd.read_sql('select * from country limit 5', db)
df1

I need to create a table name with country2 and update the df1 out to country2


Solution

  • Use Pandas to_sql (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html). This should work for you:

    import mymysql
    from sqlalchemy import create_engine
    sql_table_name = 'country2'
    engine = create_engine("mysql://testuser:test123@localhost:0/world") # creat engine
    df1.to_sql(sql_table_name, engine) # add to table