postgresql
  • python-3.x
  • psycopg2
  • 2016-12-01 124 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,因爲前者會在整個交易中發生變化。

    最好避免讓交易繼續運行,因爲它們可以捆綁服務器所需的資源。

    相關問題