Home Insert list of dictionaries and variable into table
Reply: 0

Insert list of dictionaries and variable into table

user1096
1#
user1096 Published in June 21, 2018, 1:00 am
lst = [{'Fruit':'Apple','HadToday':2},{'Fruit':'Banana','HadToday':8}]

I have a long list of dictionaries of the form above.
I have two fixed variables.

person = 'Sam'
date = datetime.datetime.now()

I wish to insert this information into a mysql table.

How I do it currently

for item in lst:
    item['Person'] = person
    item['Date'] = date

cursor.executemany("""
    INSERT INTO myTable (Person,Date,Fruit,HadToday)
    VALUES (%(Person)s, %(Date)s, %(Fruit)s, %(HadToday)s)""", lst)

conn.commit()

Is their a way to do it, that bypasses the loop as the person and date variables are constant. I have tried

lst = [{'Fruit':'Apple','HadToday':2},{'Fruit':'Banana','HadToday':8}]
cursor.executemany("""
    INSERT INTO myTable (Person,Date,Fruit,HadToday)
    VALUES (%s, %s, %(Fruit)s, %(HadToday)s)""", (person,date,lst))

conn.commit()

TypeError: not enough arguments for format string

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314353 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO