pg_connection_status
使用PQstatus来实现。psycopg不公开该API,因此该检查不可用。psycopg只能调用PQstatus本身的两个地方是在建立新连接时和执行开始时。所以是的,你需要发出一个简单的SQL语句来确定连接是否仍然存在。
import psycopg2
import subprocess
connection = psycopg2.connect(
database=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