postgresql データベースへの接続数を取得するための次のスクリプトがあります。
import psycopg2, time
db_ip = "192.168.1.137"
db_port = "5432"
db_name = "postgres"
db_username = "postgres"
db_pw = "pass"
db = psycopg2.connect("host=%s port=%s dbname=%s user=%s password=%s" % (db_ip, db_port, db_name, db_username, db_pw))
cur = db.cursor()
while True:
#~ db = psycopg2.connect("host=%s port=%s dbname=%s user=%s password=%s" % (db_ip, db_port, db_name, db_username, db_pw))
#~ cur = db.cursor()
cur.execute("SELECT count(*) FROM pg_stat_activity;")
current_connections = cur.fetchall()
print current_connections
#~ cur.close()
#~ db.close()
time.sleep(1)
cur.close()
db.close()
実際の接続数は変動しますが、while ループの反復ごとに接続を再確立する行のコメントを外さない限り、スクリプトは初期値を繰り返し返すだけです。
これは仕様によるものですか、それとも何か不足していますか? 理想的には、接続を一度確立してから、単純にクエリを実行することをお勧めします。
ご指導いただきありがとうございます。