如何将数据帧输出插入 mysql

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

我需要用 country2 创建一个 table 名称并将 df1 更新为 country2

一定要检查 SqlAlchemy。使用SqlAlchemy写一个Mysql交互class。 SqlAlchemy 允许使用 python 连接数据库。将您的数据帧编码为更新插入 sql 字符串。然后使用 cursor.execute(query_string) 进行更新插入。

engine = sqlalchemy.create_engine(
    'mysql+mysqlconnector://user:pwd@hostname/db_name',
    connect_args={'auth_plugin': 'mysql_native_password'})

sample_sql_database = df.to_sql('table_name', con=engine)

可以选择 "append" 来自数据框的竞争或 "replace" 也

sample_sql_database =  df.to_sql('table_name', engine, if_exists='replace')
sample_sql_database =  df.to_sql('table_name', engine, if_exists='append')

参考:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html

使用Pandas to_sql (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html)。这应该适合你:

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