使用 Python 访问数据库时,连接在操作过程中关闭

Aki*_*ira 9 python database postgresql heroku asyncpg

除了我的 python bot 之外,我还使用 Heroku 设置了一个 postgresql 服务器,它也在 heroku 上运行,但该 bot 无法连接到数据库

我确保密码用户名等正确。

这是用于连接的方法:

async def create_db_pool():
    bot.pg_con = await asyncpg.create_pool(database="dbname", 
    user="username", 
    password="dbpw")
Run Code Online (Sandbox Code Playgroud)

这就是我运行它的方式:

bot.loop.run_until_complete(create_db_pool())
Run Code Online (Sandbox Code Playgroud)

预计访问数据库并写入和读取数据,而不是我收到以下错误:

asyncpg.exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation
Task was destroyed but it is pending!
task: <Task pending coro=<chng_pr() running at I:/Python/HardCoreDisBot/Commands.py:38> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000002571E9B1978>()]>>
Run Code Online (Sandbox Code Playgroud)

小智 2

所以我查看了你的问题,发现了一个有类似问题的线程,他们似乎通过输入max_inactive_connection_lifetime这样的代码找到了解决方法。是该线程的链接。

async def create_db_pool():
    bot.pg_con = await asyncpg.create_pool(database="dbname", 
    user="username", 
    password="dbpw",
    max_inactive_connection_lifetime=3)
Run Code Online (Sandbox Code Playgroud)