【发布时间】: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 参数占位符创建一个参数值列表。