I am having trouble inserting multiple values into a postgres table with python's psycopg2 executemany() function. I have a dict with the following values:
{u'city': u'14000', u'sitename': u'12298', u'longitude': u'-9767764.18643674', u'county': u'17031', u'sourceid': u'42', u'state': u'17', u'latitude': u'5147311.10876352', u'csrfmiddlewaretoken': u'WY7EBHl55TuWSwXv4C3vNa5X5d0peJyv', u'sourcesiteid': u'42' }
which I am attempting to insert with the following code:
try:
con = psycopg2.connect(db_connect)
cur = con.cursor()
cur.executemany("""INSERT INTO cacw_sites(sourceid,sitename,sourcesiteid,state,county,city,schooldistrict,zipcode,neighborhood,latitude,longitude)
VALUES ( %(sourceid)s, %(sitename)s, %(sourcesiteid)s, %(state)s, %(county)s, %(city)s, %(zipcode)s, %(neighborhood)s,
%(latitude)s, %(longitude)s)""", dict)
con.commit()
except psycopg2.DatabaseError, e:
print 'There was a problem updating the sites: %s'%e
finally:
if con:
con.close()
However, I keep receiving the error: TypeError: string indices must be integers
I realize that I am somehow trying to reference a string with another string but I am not sure where. If I do
dict['state']
I recieve the proper output of
u'17'
So how come I cannot seem to insert these values correctly? Thank you for your help!
cur.executemany(..., [dict]).executemanyexpects a list of lists or dicts.