postgresql
  • python-3.x
  • psycopg2
  • 2016-12-01 123 views 1 likes 
    1

    当我执行普通选择时,会返回正确的结果,但是当我执行此选择以进行数据库正常运行时,它始终返回相同的第一个结果。我没有检查Postgres日志,我发现select被执行。为什么psycopg2为重复的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() 
    
    
    +1

    是'autocommit' off?.. –

    回答

    2

    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,因为前者会在整个交易中发生变化。

    最好避免让交易继续运行,因为它们可以捆绑服务器所需的资源。

    相关问题