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

1 投票
1 回答
1274 浏览
提问于 2025-04-18 13:46

我有一段代码,它会循环执行,每次都往表格里添加一行信息。不过,我发现每一行的时间戳都是一样的,都是第一行的时间戳。这让我觉得,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作为数据库。

1 个回答

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()) 

撰写回答