当我执行普通 Select 时返回正确的结果,但是当我执行此 select for DB uptime 时它始终返回相同的第一个结果。我确实检查了 Postgres 日志,我看到 select 被执行了。
#!/usr/bin/python3 import psycopg2 from time import sleep conn = psycopg2.connect("dbname='MyDB' user='root' host='127.0.0.1' password='********'") cur = conn.cursor() def test(): e = 0 while e != 100: cur.execute("SELECT date_trunc('second', current_timestamp - pg_postmaster_start_time()) as uptime;") uptv = cur.fetchone() print(uptv) e += 1 sleep(0.1) test()
最佳答案
Per the documentation, current_timestamp
returns the timestamp at the start of the transaction . SQL 标准要求此行为。
psycopg2
在您运行查询时开始事务。它不会自动提交。因此,除非您 conn.commit()
,否则相同的 xact 将针对第一个查询和您以后的迭代运行。
你应该:
conn.commit()
在每次查询之后(或者如果您愿意,conn.rollback()
如果它是只读的并且不做任何更改);或- 使用
clock_timestamp()
而不是current_timestamp
,因为前者会在整个交易过程中发生变化。
无论如何最好避免让事务继续运行,因为它们会占用服务器所需的资源。
关于postgresql - 为什么 psycopg2 对重复的 SELECT 返回相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40906323/