MySQLdb executemany using a list as input?

寵の児 提交于 2019-12-23 14:01:44

问题


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

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

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.


回答1:


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


来源:https://stackoverflow.com/questions/10180335/mysqldb-executemany-using-a-list-as-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!