我有一个 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 数据库连接处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!