Making sure that psycopg2 database connection alive(确保 psycopg2 数据库连接处于活动状态)
问题描述
我有一个 python 应用程序,它打开一个可以在线挂起一个小时的数据库连接,但有时数据库服务器会重新启动,虽然 python 仍然有连接,但它不会与 OperationalError
异常一起工作.
I have a python application that opens a database connection that can hang online for an hours, but sometimes the database server reboots and while python still have the connection it won't work with OperationalError
exception.
所以我正在寻找任何可靠的方法来ping"数据库并知道连接是活动的.我检查了 psycopg2 文档,但找不到类似的东西.当然,我可以发出一些简单的 SQL 语句,例如 SELECT 1
并捕获异常,但我希望有一个本地方法,例如 PHP pg_connection_status
So I'm looking for any reliable method to "ping" the database and know that connection is alive. I've checked a psycopg2 documentation but can't find anything like that. Sure I can issue some simple SQL statement like SELECT 1
and catch the exception, but I hope there is a native method, something like PHP pg_connection_status
谢谢.
推荐答案
pg_connection_status
是使用PQstatus实现的.psycopg 不公开该 API,因此检查不可用.psycopg 调用 PQstatus 本身的唯一两个地方是建立新连接时和开始执行时.所以是的,您需要发出一个简单的 SQL 语句来确定连接是否仍然存在.
pg_connection_status
is implemented using PQstatus. psycopg doesn't expose that API, so the check is not available. The only two places psycopg calls PQstatus itself is when a new connection is made, and at the beginning of execute. So yes, you will need to issue a simple SQL statement to find out whether the connection is still there.
这篇关于确保 psycopg2 数据库连接处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:确保 psycopg2 数据库连接处于活动状态


基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01