我有以下代码:
import pandas as pd
import numpy as np
import MySQLdb
from sqlalchemy import create_engine
df = pd.read_csv('pricelist.csv')
old_df = df[['date','time','old_price']]
new_df = df[['date','time','new_price']]
engine = create_engine('mysql+mysqldb://root:python@localhost:3306/pricedb', echo = False)
old_df.to_sql(name='temporary_table_old', con=engine, if_exists = 'append', index=False)
new_df.to_sql(name='temporary_table_new', con=engine, if_exists = 'append', index=False)
with engine.begin() as cnx:
sql_insert_query_old = 'REPLACE INTO oldlist (SELECT * FROM temporary_table_old)'
sql_insert_query_new = 'REPLACE INTO newlist (SELECT * FROM temporary_table_new)'
cnx.execute(sql_insert_query_old)
cnx.execute(sql_insert_query_new)
cnx.execute("DROP TABLE temporary_table_old")
cnx.execute("DROP TABLE temporary_table_new")
上面的代码可以工作,但是可以简化上面的cnx.execute和sql_insert_query_'x'(“ with”块)的代码。我不确定性能是否明智,执行和插入这么多行会导致性能下降。我的代码最终将包含大量这些行,以从Pandas数据框中提取某些列并插入MySQL数据库。
我曾经尝试过使用Google,但这并没有太大帮助。
非常感谢!