我有一个循环遍历并返回 3 个单独的 dataframe
对象的函数。
如何将这 3 个 dataframe
对象放入具有 3 个单独的 table
的 1 个 .db
文件中?
下面的代码是我目前使用的。它循环遍历我拥有的每个项目,执行必要的操作并返回一个 Dataframe
对象,之后我可以将其放入 sql。
for each_item in items:
engine = create_engine("sqlite:///" + my_variable_database_name + ".db", echo=False)
connection = engine.connect()
pandas.DataFrame.to_sql(my_function(each_item), each_item, con=engine, if_exists="replace")
connection.close()
print(each_item + " has been completed successfully.")
print("All completed.")
我应该怎么做呢?
最佳答案
我意识到我做错了什么。基本上我只需要重组我的代码。我之前所做的是将 engine
放入循环中,并将名称设置为 each_item
而不是我的特定数据库。
engine = create_engine("sqlite:///mydatabase.db", echo=False)
for each_item in items:
connection = engine.connect()
pandas.DataFrame.to_sql(my_function(each_item), name=each_item, con=engine, if_exists="replace")
connection.close()
print(each_item + " has been completed successfully.")
print("All completed.")
关于python - 如何使用 pandas/sqlalchemy 在 .db 文件中创建多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786798/