首页 > 解决方案 > 有什么方法可以在 python 中使用 MySQL 来持久化 Pandas 数据帧中的数据?

问题描述

有什么方法可以在 python 中使用 MySQL 来持久化 Pandas 数据帧中的数据。

标签: pythonmysqlpandas

解决方案


是的,你可以使用 sqlalchemy,

import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
import pymysql

engine = create_engine('mysql+mysqlconnector://[user]:[pass]@[host]:[port]/[schema]', 
 echo=False)
df.to_sql(name='sample_table2', con=engine, if_exists = 'append', index=False)

带有 pymysql 连接器

# Connect to the database
connection = pymysql.connect(host='localhost', user='root', password='root', db='test')
cursor = connection.cursor()
# connection is not autocommit by default. So we must commit to save our changes.
connection.commit()

engine = create_engine(f"mysql+pymysql://root:root@localhost/test"
                    .format(user="root",
                            pw="root",
                            db="test"))
df.to_sql(name='sample_table2', con=engine, if_exists = 'append', index=False)

推荐阅读