Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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:
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!
You are using executemany()
which expects a sequence of dictionaries, but give it just a dictionary.
cur.execute(
"""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)
instead.
What happens instead is that the database adapter loops over the dictionary object, which yields keys (each a string), then tries to find your parameters on those strings. You end up trying to do the equivalent of 'sourceid'['sourceid']
that way.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.