简体   繁体   中英

Updating timestamp each time a row is added?

I have code that loops, adding a row with information to each row. However, I find that each row does not have a new timestamp, but rather has the same one as the very first row, leading me to believe that the value of current_timestamp is not updating each time. Thus, what fix this problem? Here is my code:

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


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

my insert function:

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

This code is in python, btw, and it is using postgresql for database stuff.

The immediate fix is to commit after each insert otherwise all of the inserts will be done inside a single transaction

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

Since these functions return the start time of the current transaction, their values do not change during the transaction. This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the "current" time, so that multiple modifications within the same transaction bear the same time stamp.

Those functions should not be passed as parameters but included in the SQL statement

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

The best practice is to keep the commit outside of the loop to have a single transaction

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

and use the statement_timestamp function which, as the name implies, returns the statement timestamp in instead of the transaction beginning timestamp

INSERT INTO test1 (ID, date, timestamp)
values (%s, statement_timestamp()::date, statement_timestamp()) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM