Skip to main content
 首页 » 编程设计

python之尝试将 dict 值插入 postgresql 表时出现类型错误

2025年05月04日9wuhuacong

我无法使用 python 的 psycopg2 executemany() 函数将多个值插入到 postgres 表中。我有一个具有以下值的字典:

{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() 

但是,我一直收到错误:TypeError: string indices must be integers

我意识到我正在尝试用另一个字符串引用一个字符串,但我不确定在哪里。如果我这样做

dict['state'] 

我收到了

的正确输出
u'17' 

那么为什么我似乎无法正确插入这些值? 感谢您的帮助!

请您参考如下方法:

您正在使用 executemany(),它需要字典的序列,但只给它一个字典。

使用:

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) 

相反。

取而代之的是,数据库适配器循环遍历字典对象,它产生键(每个键都是一个字符串),然后尝试在这些字符串上找到您的参数。您最终会尝试以这种方式执行与 'sourceid'['sourceid'] 相同的操作。