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 数据库连接处于活动状态
基础教程推荐
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
