【问题标题】:Writing a dataframe from Python to MySQL将数据框从 Python 写入 MySQL
【发布时间】:2017-02-21 14:50:35
【问题描述】:

我有一个从 API 下载数据并将所有这些信息转换为 CSV 的脚本。我需要将这些数据放入 MySQL 中的表中(我已经创建了它并建立了与 MySQL 连接器的连接)。有没有办法做到这一点?

【问题讨论】:

标签: python mysql pandas dataframe


【解决方案1】:

Pandas.DataFrame 有一个方法 to_sql 将数据帧写入 sql 表。

使用该方法的最简单方法是使用 sqlalchemy 创建连接。(您需要安装mysql-python)并使用.to_sql 将数据读入表中。

from sqlalchemy import create_engine
engine = create_engine('mysql://username:password@host:port/database') #change to connect your mysql
#if you want to append the data to an existing table
df.to_sql(name='SQL Table name',con=engine,if_exists='append',index=False) 

#if you want to create a new table 
df.to_sql(name='New SQL Table name',con=engine,if_exists='fail',index=False) 

请注意,如果您事先创建了表格,则需要使用参数dtype 来定义表格列的数据类型。

【讨论】:

  • @PaulaC,很高兴我能提供帮助。请务必接受我的回答。
猜你喜欢
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 2021-12-03
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
相关资源
最近更新 更多