有什么办法可以在python中使用MySQL来保留来自Pandas数据框的数据?

时间:2019-11-14 05:37:22

标签: python mysql pandas

有什么方法可以在python中使用MySQL来保留来自Pandas数据帧的数据。

1 个答案:

答案 0 :(得分:0)

是的,您可以使用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)