【问题标题】:How to write JSON column to MySQL using pandas.to_sql?如何使用 pandas.to_sql 将 JSON 列写入 MySQL?
【发布时间】:2022-01-02 17:06:40
【问题描述】:

我尝试使用 SQLAlchemy 和 pandas 的 to_sql 将包含 JSON 列的表保存到 MySQL 中挣扎了很长时间。

我收到了这个错误

sqlalchemy.exc.ProgrammingError: (mysql.connector.errors.ProgrammingError) Failed processing pyformat-parameters; Python 'list' cannot be converted to a MySQL type

当尝试按照以下标准方式进行操作时。我有一个 pandas 数据框 (df),其中有两列包含 JSON('videos' 和 'newsitems')。

import sqlalchemy
connection = sqlalchemy.create_engine(f"mysql+mysqlconnector://{user}:{pw}@{host}/{db}")
table_name = 'TABLENAME'
df.to_sql(table_name, 
          connection, 
          if_exists='append', 
          index=False)

【问题讨论】:

    标签: python mysql pandas sqlalchemy


    【解决方案1】:

    现在我在其他地方找到了关于 postgresql 的回复——它与 MySQL 一样好用。添加最后两行 dtype={...} 解决了这个问题

    import sqlalchemy
    connection = sqlalchemy.create_engine(f"mysql+mysqlconnector://{user}:{pw}@{host}/{db}")
    table_name = 'TABLENAME'
    df.to_sql(table_name, 
              connection, 
              if_exists='append', 
              index=False,
              dtype={'videos': sqlalchemy.types.JSON,
                     'newsitems': sqlalchemy.types.JSON})
    

    帮助我解决问题的原始问答是这样的

    Writing JSON column to Postgres using Pandas .to_sql

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2017-12-31
      • 2017-05-19
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多