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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…