每次添加行时更新时间戳?

时间:2014-07-17 20:26:47

标签: python postgresql timestamp psycopg2

我有循环的代码,向每行添加一行信息。但是,我发现每一行都没有新的时间戳,而是与第一行具有相同的时间戳,这使我相信current_timestamp的值不会每次都更新。那么,是什么解决了这个问题?这是我的代码:

if __name__ == "__main__":
    main()
    deleteAll()   # Clears current table


    ID = 0
    while ID < 100:          
        insert(ID, 'current_date', 'current_timestamp')
        ID += 1
    conn.commit()        

我的插入功能:

def insert(ID, date, timestamp): # Assumes table name is test1
    cur.execute(
    """INSERT INTO test1 (ID, date,timestamp) VALUES (%s, %s, %s);""", (ID, AsIs(date), AsIs(timestamp))) 

这段代码是python,btw,它使用postgresql作为数据库的东西。

1 个答案:

答案 0 :(得分:1)

每次插入后立即修复commit否则所有插入都将在单个事务中完成

while ID < 100:          
    insert(ID, 'current_date', 'current_timestamp')
    ID += 1
    conn.commit()        

http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT

  

由于这些函数返回当前事务的开始时间,因此它们的值在事务期间不会更改。这被认为是一个特征:目的是允许单个事务具有“当前”时间的一致概念,以便同一事务中的多个修改具有相同的时间戳。

这些函数不应作为参数传递,而应包含在SQL语句

def insert(ID): # Assumes table name is test1
    cur.execute("""
        INSERT INTO test1 (ID, date, timestamp)
        VALUES (%s, current_date, current_timestamp);
    """, (ID,)
    ) 

最佳做法是将commit保留在循环之外以进行单个事务

while ID < 100:          
    insert(ID)
    ID += 1
conn.commit()        

并使用statement_timestamp函数,顾名思义,它返回语句时间戳而不是事务开始时间戳

INSERT INTO test1 (ID, date, timestamp)
values (%s, statement_timestamp()::date, statement_timestamp()) 
相关问题