MySQLdb executemany使用列表作为输入?

时间:2012-04-16 19:24:17

标签: python mysql-python

我想在我的程序中使用executemany来同时存储20条记录,这是文档中的内容......

c.executemany(
  """INSERT INTO breakfast (name, spam, eggs, sausage, price)
  VALUES (%s, %s, %s, %s, %s)""",
  [
  ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
  ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
  ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
  ] )

但是,我在列表中有我的值,而不是使用我列表中的索引来执行上述的18个版本。

以下是我的代码......

db = connect_to_db()
cursor = db.cursor()
sql = "INSERT INTO gkey (keyword, date, time, position) VALUES (%s, %s, %s, %s)"
params = [(str(keywords[0]), date, time, position[0])]
cursor.executemany(sql, params)
db.commit()

这很好用,它会提交列表中的第一个关键字,以及日期,时间和位置,我不想像下面那样重复19次参数...

db = connect_to_db()
cursor = db.cursor()
sql = "INSERT INTO gkey (keyword, date, time, position) VALUES (%s, %s, %s, %s)"
params = [
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])    
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])

]
cursor.executemany(sql, params)
db.commit()

上面我想避免的一个例子(索引需要递增才能使它工作我知道!;)

当我尝试将整个列表作为值传递时,我收到错误,我需要一次传递一个,任何想法?可以执行多次这样做,还是应该循环并一次更新一个?但我很确定我尝试过这个并且得到了类似的错误?我没注意到它。

1 个答案:

答案 0 :(得分:10)

params = [(str(keywords[i]), date, time, position[i]) for i in range(20)]