如何通过Python更新MySQL中的时间戳字段?

时间:2015-02-20 19:35:58

标签: python mysql mysql-python

我有以下架构的数据库表,

模式

  

hash VARCHAR(32) NOT NULL, regional_unit VARCHAR(64) NOT NULL, url VARCHAR(2048) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00', updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW(), PRIMARY KEY (hash)

我通过Python使用以下语句更新:

查询

INSERT INTO urls (hash, regional_unit, url, created_at, updated_at)
    VALUES (%s, %s, %s, %s, %s)
    ON DUPLICATE KEY UPDATE hash=hash;
    [['...', '...', '...', None, datetime.datetime(2015, 2, 20, 21, 18, 55, 910026)],
     ['...', '...', '...', None, datetime.datetime(2015, 2, 20, 21, 18, 55, 910046)]]

我的问题是,根据上述陈述,字段'created_at'不会更新,即它始终与'created_at'字段具有相同的值。

修改

INSERT INTO urls (hash, regional_unit, url, created_at, updated_at) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE hash=hash; [['...', '...', '...', datetime.datetime(2015, 2, 20, 22, 12, 57, 268424), datetime.datetime(2015, 2, 20, 22, 12, 57, 268437)], ['...', '...', '...', datetime.datetime(2015, 2, 20, 22, 12, 57, 268444), datetime.datetime(2015, 2, 20, 22, 12, 57, 268446)]]

EDIT2:

self.db_connect()
self.get_curs().executemany("""INSERT INTO urls (hash, regional_unit, url, created_at, updated_at) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE hash=hash;""", [['...', '...', '...', datetime.datetime(2015, 2, 20, 22, 12, 57, 268424), datetime.datetime(2015, 2, 20, 22, 12, 57, 268437)], ['...', '...', '...', datetime.datetime(2015, 2, 20, 22, 12, 57, 268444), datetime.datetime(2015, 2, 20, 22, 12, 57, 268446)]])
self.get_conn().commit()
self.db_disconnect()

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

a = datetime.datetime(2015, 2, 20, 22, 12, 57, 268437).strftime('%Y-%m-%d %H:%M:%S')

self.get_curs().executemany("""INSERT INTO urls (hash, regional_unit, url, created_at, updated_at) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE hash=hash;""", [['...', '...', '...', a, a], ['...', '...', '...', a,a]])