【问题标题】:python mysqldb update where variable where in list [duplicate]python mysqldb更新列表中的变量位置[重复]
【发布时间】:2013-11-22 13:09:53
【问题描述】:

我正在尝试根据列表中的变量更新字段...

urls = ["aaa", "bbb", "ccc", ...] (long list)
time_now = time.strftime('%Y-%m-%d %H:%M:%S')

UPDATE table SET updated_at=time_now WHERE name IN list

你会如何在 python 中做到这一点?

这是我目前的代码:

update_time = time.strftime('%Y-%m-%d %H:%M:%S')
urls = ["http://asdf", "http://qwer"]
cur.execute('UPDATE sales SET updated_at=%s WHERE sale_url IN (%s)', (time_now, urls))

【问题讨论】:

  • MySQL数据库适配器使用%s而不是?,因为它使用不同的SQL参数样式,否则原理完全相同。
  • 我的问题是在使用 where in 的同时将 updated_at 设置为变量的语法...
  • 您不能为此使用 sql 参数吗? cursor.execute('UPDATE table SET updated_at=%s WHERE name in ({})'.format(...), [time_now] + long_list).
  • 这里 [time_now] + long_list 为 SQL 参数占位符创建一个参数值列表。

标签: python mysql


【解决方案1】:

试试;

"UPDATE table SET updated_at='%s' WHERE name IN ('%s')" % (time_now, "', '".join(list))

【讨论】:

    猜你喜欢
    • 2013-02-21
    • 2021-11-18
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 2014-02-03
    相关资源
    最近更新 更多