Skip to content Skip to sidebar Skip to footer

Python: Adding Named Tuples To MySQL In A For Loop

So I have the following namedtuple, containing multiple items: [item(company='MARINE AND GENERAL MUTUAL LIFE ASSURANCE SOCIETY', google_name='no results', place_id='no results', fo

Solution 1:

Assuming item really is a namedtuple and deducing from the order of arguments that it's declared like

item = namedtuple('item', 'company google_name place_id formatted_address')

there's no need to use named placeholders in your query, unless you really want to. Just use the normal sequence formatting style that works with tuples:

# assuming items is a reference to the list of item instances you gave
# in the example
cursor.executemany("INSERT INTO place_id "
                   "(company, google_name, place_id, formatted_address) "
                   "VALUES (%s, %s, %s, %s)", items)

To use the named placeholder version you could convert the list of items to a sequence of OrderedDicts (a sequence of mappings) with namedtuple._asdict, but there's really no need for this:

cursor.executemany("INSERT INTO place_id "
                   "(company, google_name, place_id, formatted_address) "
                   "VALUES (%(company)s, %(google_name)s, %(place_id)s, %(formatted_address)s",
                   (i._asdict() for i in items))

Solution 2:

Using 'named' style parameter markers (such as '%(company)s') in the query requires that you pass a mapping with the necessary keys to cursor.execute(). Since you pass it a tuple, you need to change the markers accordingly (e.g. use the 'format' style):

for i in items:
    cursor.execute("INSERT INTO place_id (company, google_name, place_id, "
                   "formatted_address) VALUES (%s, %s, %s, %s)", i)

or using cursor.executemany():

cursor.executemany("INSERT INTO place_id (company, google_name, place_id, "
                   "formatted_address) VALUES (%s, %s, %s, %s)", items)

Post a Comment for "Python: Adding Named Tuples To MySQL In A For Loop"