确保psycopg2数据库连接活着 [英] Making sure that psycopg2 database connection alive

查看:496
本文介绍了确保psycopg2数据库连接活着的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python应用程序打开一个数据库连接,可以挂在线一个小时,但有时数据库服务器重新启动,而python仍然有连接,它将无法使用 OperationalError exception。

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

谢谢。 p>

Thanks.

推荐答案

pg_connection_status 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数据库连接活着的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆