【问题标题】:How can I update a timestamp field in MySQL through Python?如何通过 Python 更新 MySQL 中的时间戳字段?
【发布时间】:2015-02-20 19:35:57
【问题描述】:

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

架构

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

【问题讨论】:

  • created_at 是您在查询中的第四个字段,出于某种原因您已将其设置为 None ;-)
  • 没有。不幸的是,这似乎不是问题。我编辑了我的问题,但仍然遇到同样的问题......
  • 但是这是python代码吗?我没有看到 python 结构。并且看不到查询字符串。你混合了一切。展示你使用的真实python代码
  • 好的,我也引用了我的python代码。请看看你不介意:)
  • @KimAlexander 请看看EDIT2 :)

标签: python mysql mysql-python


【解决方案1】:

试试这个方法:

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

【讨论】:

  • 很遗憾,这也不起作用......我还应该尝试什么?
  • 所以在你开始插入之前你的表是空的?它会插入除created_at之外的所有内容?
  • 第一次运行查询时,我的表确实是空的。但是第二次,当表已经有一条记录时,由于某种原因,字段 updated_at 没有得到更新......有什么想法吗?
  • 好吧,你的意思不是很痛...从技术上讲,我不使用 UPDATE 而是使用 INSERT 的特殊情况。
  • 是的,但是你写了ON DUPLICATE...UPDATE hash...所以你甚至没有尝试更新除hash之外的任何字段,甚至没有尝试更新的哈希值更新,您只是要求保留旧值
猜你喜欢
  • 1970-01-01
  • 2015-08-01
  • 2021-04-19
  • 2012-11-14
  • 2014-08-11
  • 1970-01-01
  • 2013-06-27
  • 2012-12-10
  • 2015-11-19
相关资源
最近更新 更多