Skip to content
Advertisement

Making sure that psycopg2 database connection alive

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.

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

Thanks.

Advertisement

Answer

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.

Advertisement