【问题标题】:Type error when attempting to insert dict values into postgresql table尝试将 dict 值插入 postgresql 表时键入错误
【发布时间】:2014-02-28 02:59:31
【问题描述】:

我无法使用 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'

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

【问题讨论】:

  • 试试:cur.executemany(..., [dict])executemany 需要一个列表或字典列表。

标签: python dictionary psycopg2


【解决方案1】:

您正在使用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'] 等效的操作。

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2018-04-26
    相关资源
    最近更新 更多