postgresql - 为什么 psycopg2 对重复的 SELECT 返回相同的结果?

标签 postgresql python-3.x psycopg2

当我执行普通 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/

相关文章:

postgresql - 在 Doctrine2 中配置原生 Point PostgreSQL 类型

postgresql - COLLATE pg_catalog ."default"对 postgres 数据库表中的文本属性做了什么?

python-3.x - 通过 concurrent.futures 多处理填充 numpy 数组

python-3.x - 无法通过cv2.imread()在gcloud的tmp中读取图像,它不返回任何内容

python - 每个结果的多个子查询,如何更快?

python - 将dict对象添加到postgresql

sql - 需要超快的 postgresQL 查询

php - 如何在 postgresql 上使用 unix 时间戳

python-3.x - 使用 OpenCV 为 png 设置白色背景而不是透明度

python - 在 python 工作流中调整 Postgresql 性能和内存使用