【问题标题】:Updating timestamp each time a row is added?每次添加一行时更新时间戳?
【发布时间】:2014-07-17 20:26:47
【问题描述】:

我有循环的代码,向每一行添加一行信息。但是,我发现每一行都没有新的时间戳,而是与第一行相同,这让我相信 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 中,顺便说一句,它使用 postgresql 处理数据库。

【问题讨论】:

  • 时间戳字段的类型是什么。 mysql timestamp-type 字段完全符合您的要求。但是,如果您的 timestamp 字段实际上是 datetime 类型,那么您每次都必须使用触发器或使用新值手动更新它。
  • 什么是AsIs('current_timestamp')?
  • @MarcB 是的,它是一个日期时间类型。你知道如何每次手动更新一个新值吗?我认为它已经这样做了,但我不确定它是一个日期时间类型如何改变它。谢谢!
  • 把它改成timestamp类型,mysql会在你update记录的任何时候自动为你更新。

标签: python postgresql timestamp psycopg2


【解决方案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()) 

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多