python - 如何使用 pandas/sqlalchemy 在 .db 文件中创建多个表

标签 python pandas sqlalchemy

我有一个循环遍历并返回 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/

相关文章:

python - 为什么在连接两个字符串时 Python 比 C 快?

python - pd.to_json() 中的格式数字

python - 如何计算 pandas 中事件之间的时间

python - Tornado 的 ORM

python - SQLAlchemy : how can I execute a raw INSERT sql query in a Postgres database?

python - 导入禁用图形的 Pandas

python - 无法使用 Python 请求 session 模块登录网站

python - Python 中的 HLS Live Stream API 从磁盘提供文件

python - 在 Python 中从 Dataframe 更新字典非常慢

python - 为什么这个查询会根据我如何安排 DateTime 算法给出不同的结果?