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)
在运行SQLSELECT语句时,我甚至使用了df.read_sql()
命令也得到了这个结果。把它改成原来的df.read_sql_query()
包起来,去掉了它。我怀疑那里会有某种联系
所以,问题是,在未来的版本中,我如何将dataframe表写入SQL而不被弃用?“使用上下文管理器”是什么意思,我如何实现它
版本:
熊猫:1.1.5 | SQLAlchemy:1.4.0 | pyodbc:4.0.30 | Python:3.8.0
使用mssql数据库。
操作系统:LinuxMintXFCE,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调用之间保持“活动”,并允许我使用池连接,而不必重新连接
更新:根据熊猫团队的说法,这将在熊猫1.2.4中得到修正,截至撰写本文时,该版本尚未发布
添加此作为答案,因为谷歌在这里领先,但接受的答案不适用
使用Pandas的周围代码使用上下文管理器:
在我的例子中,这个错误是从pandas本身抛出的,而不是在使用pandas的周围代码中抛出的:
熊猫本身的片段是:
我提出了一个问题:https://github.com/pandas-dev/pandas/issues/40825
你可以试试
这种方法使用
ContextManager
。引擎的ContextManager
返回一个连接,并自动调用该连接上的connection.close()
,see。阅读有关ContextManager
{a2}的更多信息。要知道的另一件有用的事情是,连接也是一个ContextManager
,为您处理事务。这意味着它开始和结束一个事务,如果出现错误,它会自动调用回滚相关问题 更多 >
编程相关推荐