Pandas离开空闲的Postgres连接后打开到\u sql?

2024-04-19 12:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我用熊猫和博士后做了很多ETL。我有大量空闲的连接,其中很多都标有COMMIT和{},我不知道如何防止长时间处于空闲状态而不是关闭。我用来写入数据库的主要代码是使用pandasto_sql

def write_data_frame(self, data_frame, table_name):
    engine = create_engine(self.engine_string)
    data_frame.to_sql(name=table_name, con=engine, if_exists='append', index=False)

我知道这绝对不是PostgreSQL的最佳实践,我应该做一些类似于将参数传递给存储过程或函数之类的事情,但这就是我们从非Postgres数据库/数据源获取数据帧并上传到Postgres的方法。在

我的pgAdmin看起来像这样:

enter image description here

有人能给我指出一个正确的方向,如何避免未来如此多的空闲连接?我们的一些数据库连接是长寿命的,因为它们是连续的“批处理”过程。但是,似乎有些一次性事件让连接变得开放和闲置。在


Tags: 代码nameself数据库sqldata过程状态
1条回答
网友
1楼 · 发布于 2024-04-19 12:35:26

一次性使用engine可能不太适合您。如果可能,可以将引擎作为类的成员,并将其称为self.engine。在

另一个选择是显式地处理引擎。在

def write_data_frame(self, data_frame, table_name):
    engine = create_engine(self.engine_string)
    data_frame.to_sql(name=table_name, con=engine, if_exists='append', index=False)
    engine.dispose()

the docs所述

This has the effect of fully closing all currently checked in database connections. Connections that are still checked out will not be closed, however they will no longer be associated with this Engine, so when they are closed individually, eventually the Pool which they are associated with will be garbage collected and they will be closed out fully, if not already closed on checkin.

这也可能是try...except...finally块的一个很好的用例,因为只有在前面的代码没有错误地执行时,.dispose才会被调用。在

我更愿意建议你通过这样的连接:

^{pr2}$

但是to_sql文档表示您不能这样做,它们只接受engine

相关问题 更多 >