【问题标题】:pandas to_sql() gives a SADeprecationWarningpandas to_sql() 给出了 SADeprecationWarning
【发布时间】:2021-06-15 05:05:50
【问题描述】:

pandas 中的 to_sql() 函数现在正在生成 SADeprecationWarning。

df.to_sql(name=tablename, con=c, if_exists='append', index=False )

[..]/lib/python3.8/site-packages/pandas/io/sql.py:1430: SADeprecationWarning:The Connection.run_callable() method is deprecated and will be removed in a future release.  Use a context manager instead. (deprecated since: 1.4)

在运行 sql select 语句时,即使使用 df.read_sql() 命令,我也得到了这个。将其更改为它所环绕的原始df.read_sql_query(),摆脱它。我怀疑那里会有一些联系。

所以,问题是,我如何将数据帧表写入 SQL,而不会在未来的版本中被弃用? “使用上下文管理器”是什么意思,我该如何实现?

版本:
熊猫:1.1.5 | SQLAlchemy:1.4.0 | pyodbc:4.0.30 | Python:3.8.0
使用 mssql 数据库。
操作系统:Linux Mint Xfce,18.04。使用 python 虚拟环境。

如果重要,连接创建如下:

conn_str = r'mssql+pyodbc:///?odbc_connect={}'.format(dbString).strip()
sqlEngine = sqlalchemy.create_engine(conn_str,echo=False, pool_recycle=3600)
c = sqlEngine.connect()

在db操作之后,

c.close()

这样做可以使主连接 sqlEngine 在 api 调用之间保持“活动”,并让我使用池连接,而不必重新连接。

【问题讨论】:

    标签: python pandas dataframe sqlalchemy


    【解决方案1】:

    你可以试试……

    connection_string = r'mssql+pyodbc:///?odbc_connect={}'.format(dbString).strip()
    engine = sqlalchemy.create_engine(connection_string, echo=False, pool_recycle=3600)
    with engine.connect() as connection:
        df.to_sql(name=tablename, con=connection, if_exists='append', index=False)
    

    此方法使用ContextManager。引擎的ContextManager 返回一个连接并在其上自动调用connection.close()see。阅读更多关于ContextManagerhere。要知道的另一件有用的事情是,连接也是ContextManager 并为您处理事务。这意味着它开始和结束一个事务,如果发生错误,它会自动调用回滚。

    【讨论】:

    • 哦!那么他们为什么不那样说;)
    • 虽然这个答案有助于理解上下文管理器,但这并不能真正解决问题。问题在于,无论调用代码是否使用上下文管理器,pandas 本身都在使用已弃用的方法。
    【解决方案2】:

    更新:根据 pandas 团队的说法,这将在 Pandas 1.2.4 中修复,截至撰写本文时尚未发布。

    添加这个作为答案,因为谷歌在这里领先,但接受的答案不适用。

    我们使用 Pandas 的周边代码确实使用了上下文管理器:

    with get_engine(dbname).connect() as conn:
        df = pd.read_sql(stmt, conn, **kwargs)
        return df
    

    在我的情况下,这个错误是从 pandas 本身引发的,而不是在 使用 pandas 的周围代码中:

      /Users/tommycarpenter/Development/python-indexapi/.tox/py37/lib/python3.7/site-packages/pandas/io/sql.py:1430: SADeprecationWarning: The Engine.run_callable() method is deprecated and will be removed in a future release.  Use the Engine.connect() context manager instead. (deprecated since: 1.4)
    

    pandas 本身的 sn-p 是:

    def has_table(self, name, schema=None):
        return self.connectable.run_callable(
            self.connectable.dialect.has_table, name, schema or self.meta.schema
        )
    

    我提出了一个问题:https://github.com/pandas-dev/pandas/issues/40825

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2014-08-14
      • 2018-04-09
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 2019-12-21
      相关资源
      最近更新 更多