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.
params = [(str(keywords[i]), date, time, position[i]) for i in range(20)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With