Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 273
HardQuestions Avatar asked Aug 15 '09 13:08

HardQuestions


People also ask

Is psycopg2 connection thread safe?

Thread and process safetyThe Psycopg module and the connection objects are thread-safe: many threads can access the same database either using separate sessions and creating a connection per thread or using the same connection and creating separate cursors.

Is psycopg2 a database driver?

psycopg2 2.9. 3Psycopg is the most popular PostgreSQL database adapter for the Python programming language. Its main features are the complete implementation of the Python DB API 2.0 specification and the thread safety (several threads can share the same connection).


1 Answers

This question is really old, but still pops up on Google searches so I think it's valuable to know that the psycopg2.connection instance now has a closed attribute that will be 0 when the connection is open, and greater than zero when the connection is closed. The following example should demonstrate:

import psycopg2 import subprocess  connection = psycopg2.connect(     dbname=database,     user=username,     password=password,     host=host,     port=port )  print connection.closed # 0  # restart the db externally subprocess.check_call("sudo /etc/init.d/postgresql restart", shell=True)  # this query will fail because the db is no longer connected try:     cur = connection.cursor()     cur.execute('SELECT 1') except psycopg2.OperationalError:     pass  print connection.closed # 2 
like image 193
Jaymon Avatar answered Sep 22 '22 11:09

Jaymon