MySQLdb executemany使用列表作为输入? [英] MySQLdb executemany using a list as input?

查看:66
本文介绍了MySQLdb executemany使用列表作为输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的程序中使用一次executemany一次存储20条记录,这就是它在文档中所说的...

I am wanting to use an executemany within my program to store 20 records at once, heres what it says in the documentation...

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个版本.

However, I have my values in a list, and would rather not do 18 versions of the above, using an index on my list.

这是我的下面的代码...

Here is my code below...

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次参数...

This works fine, and it will commit the first keyword in the list, along with the date, time and position, I do not want to have to repeat the params 19 times like below...

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

上面是我要避免的示例(我需要使索引递增才能起作用!;))

Above an example of what I am trying to avoid (the index needs to be incremented for it to work I know! ;))

当我尝试将整个列表作为值传递时出现错误,我需要一次传递一次,有什么想法吗?可以执行许多操作吗,还是我应该做一个循环并一次更新一次?但是我很确定自己尝试过,并且遇到了类似的错误?我没有记下来.

I get an error when I try pass the whole list as a value, and I need to pass them one at a time, any ideas? Can execute many do this, or should I be making a loop and updating them one at a time? But I'm pretty sure I tried that and I got a similar error? I didn't note it down though.

推荐答案

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

这篇关于MySQLdb executemany使用列表作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆