2
我無法用python的psycopg2 executemany()函數將多個值插入到postgres表中。我有以下值的字典:嘗試將字典值插入postgresql表時輸入錯誤
{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' }
這我試圖用下面的代碼中插入:
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()
不過,我不斷收到錯誤:類型錯誤:字符串索引必須是整數
我意識到我在某種程度上試圖引用一個字符串與另一個字符串,但我不知道在哪裏。如果我做
dict['state']
我收到的
u'17'
適當的輸出這樣一來,我似乎怎麼也不能正確地插入這些值? 謝謝你的幫助!
嘗試:'cur.executemany(...,[dict])'。 'executemany'需要列表或字典列表。 – isedev