为什么 psycopg2 returns 重复 SELECT 结果相同?
Why psycopg2 returns same result for repeated SELECT?
当我执行普通 Select 时返回正确的结果,但是当我执行这个 select 数据库正常运行时它 returns 始终是相同的第一个结果。我确实检查了 Postgres 日志,我看到 select 被执行了。
#!/usr/bin/python3
导入 psycopg2
从时间导入睡眠
conn = psycopg2.connect("dbname='MyDB' user='root' host='127.0.0.1' password='********'")
当前 = conn.cursor()
定义测试():
e = 0
当 e != 100 时:
cur.execute("SELECT date_trunc('second', current_timestamp - pg_postmaster_start_time()) as uptime;")
uptv = cur.fetchone()
打印(uptv)
e += 1
睡眠(0.1)
测试()
Per the documentation, current_timestamp
returns the timestamp at the start of the transaction。此行为是 SQL 标准所要求的。
当您 运行 查询时,psycopg2
开始交易。它不会自动提交。因此,除非您 conn.commit()
,否则相同的 xact 是 运行ning 用于第一个查询和您以后的迭代。
你应该:
conn.commit()
在每次查询之后(或者,如果您愿意,conn.rollback()
如果它是只读的并且不做任何更改);或
- 使用
clock_timestamp()
而不是 current_timestamp
,因为前者在整个交易过程中都会发生变化。
无论如何最好避免离开事务 运行ning,因为它们会占用服务器所需的资源。
当我执行普通 Select 时返回正确的结果,但是当我执行这个 select 数据库正常运行时它 returns 始终是相同的第一个结果。我确实检查了 Postgres 日志,我看到 select 被执行了。
#!/usr/bin/python3 导入 psycopg2 从时间导入睡眠 conn = psycopg2.connect("dbname='MyDB' user='root' host='127.0.0.1' password='********'") 当前 = conn.cursor() 定义测试(): e = 0 当 e != 100 时: cur.execute("SELECT date_trunc('second', current_timestamp - pg_postmaster_start_time()) as uptime;") uptv = cur.fetchone() 打印(uptv) e += 1 睡眠(0.1) 测试()
Per the documentation, current_timestamp
returns the timestamp at the start of the transaction。此行为是 SQL 标准所要求的。
psycopg2
开始交易。它不会自动提交。因此,除非您 conn.commit()
,否则相同的 xact 是 运行ning 用于第一个查询和您以后的迭代。
你应该:
conn.commit()
在每次查询之后(或者,如果您愿意,conn.rollback()
如果它是只读的并且不做任何更改);或- 使用
clock_timestamp()
而不是current_timestamp
,因为前者在整个交易过程中都会发生变化。
无论如何最好避免离开事务 运行ning,因为它们会占用服务器所需的资源。