我有以下脚本用于检索到 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 循环的每次迭代中重新建立连接的行。
这是设计使然,还是我遗漏了什么?理想情况下,我宁愿建立一次连接,然后简单地运行查询。
提前感谢您的任何指导。