【问题标题】:Source of the ' unexpected keyword argument 'fetch' ' error in pandas to_sql?pandas to_sql 中的“意外关键字参数 'fetch'”错误的来源?
【发布时间】:2021-12-16 18:53:21
【问题描述】:

我正在尝试将数据帧上传到 Heroku postgreSQL 服务器,我之前已经成功完成了几次。

这是我的代码,for_db 是我的 Pandas 数据框的名称:

from sqlalchemy import create_engine 

engine = create_engine('postgresql://wgam{rest of url}',
                       echo=False)
  
# attach the data frame to the sql server 
for_db.to_sql('phil_nlp', 
               con = engine,
              if_exists='replace') 

起初,它无法连接,因为 Heroku 给我的服务器 URL 一开始只有“postgres”,但我知道它必须更改为“postgresql”才能正常工作并且已经克服了最初的错误.

现在我遇到了一个新错误。

/usr/local/lib/python3.7/dist-packages/sqlalchemy/dialects/postgresql/psycopg2.py in do_executemany(self, cursor, statement, parameters, context)
    899                 template=executemany_values,
    900                 fetch=bool(context.compiled.returning),
--> 901                 **kwargs
    902             )
    903 

TypeError: execute_values() got an unexpected keyword argument 'fetch'

我不明白为什么会出现这种情况。显然我从未指定过这样的关键字参数。我做了很多搜索,没有任何好的结果。有谁知道为什么它现在会在上周才起作用的代码中抛出这个错误?

【问题讨论】:

    标签: postgresql heroku


    【解决方案1】:

    能够通过添加“multi”作为方法参数来解决此问题:

    for_db.to_sql('phil_nlp', 
                       con = engine,
                      if_exists='replace',
                      index=False,
                      method='multi') 
    

    仍然不确定是什么导致了错误,但我想问题已经解决了:)

    【讨论】:

    • 虽然这适用于您的具体情况,但@jtmolon 的回答给出了一个通用的解决方案(有很好的解释),也许您应该接受他的回答。
    【解决方案2】:

    我在运行DataFrame.to_sql 方法时遇到了同样的问题。添加method='multi' 确实可以使其正常工作,并且是一个很好的解决方法。

    进一步调查它原来是我安装的 sqlalchemy 和 psycopg2 版本的问题。这些 github 问题 herehere 引导我进行以下操作。

    fetch 参数已添加到 psycopg2 version 2.8。我有 2.7 版和 sqlalchemy 1.4.15

    安装较新版本即可解决问题,无需添加method='multi' 参数。

    pip install psycopg2-binary==2.8.6
    

    希望这有助于其他人发现此问题

    【讨论】:

    • 谢谢,它帮助我解决了问题
    • 在我的情况下也有效!荣誉
    猜你喜欢
    • 2021-06-30
    • 2013-09-08
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多