2808 explained code solutions for 75 technologies


python-pandasHow to save dataframe to Mysql


from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://test:[email protected]/test?charset=utf8mb4")

import pandas as pd
df = pd.DataFrame({
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Price': [204, 304, 404, 405, 305],
  'Color': ['red', 'red', 'gray', 'black', 'red']
})

df.to_sql('phones', engine)ctrl + c
sqlalchemy

lib to work with databases

create_engine

creates database connection with specified credentials

import pandas as pd

load Pandas module

pd.DataFrame

creates Pandas DataFrame object

.to_sql(

saves current dataframe to the specified table using given db connection

'phones'

name of the table to save dataframe to (table will be automatically created)


How to save dataframe to Mysql, python pandas

Usage example

from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://test:[email protected]/test?charset=utf8mb4")

import pandas as pd
df = pd.DataFrame({
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Price': [204, 304, 404, 405, 305],
  'Color': ['red', 'red', 'gray', 'black', 'red']
})

df.to_sql('phones', engine)

print('ok, written "phones" table')
output
ok, written "phones" table