TypeError: 'dict' object does not support indexing

TypeError: 'dict' object does not support indexing

我正在处理这段代码,python 2.6.6,旧版本,因为我必须在 linux 服务器(可能是 centOS 6 或 Debian)上执行这个脚本已安装基本存储库(稳定)并且无权安装不在这些存储库中的软件。

这个片段注意select来自具有特定模式(数据库结构)的数据库(mysql)的数据,并将其插入到具有不同模式的其他数据库(postgresql)中。

cur_msql.execute("SELECT customerName, contactName, address, city, postal_code, country FROM tablename")

args_str = ','.join(cur_psql.mogrify("(%s,%s,%s,%s,%s,%s)", x) for x in cur_msql)

try:
  cur_psql.execute("INSERT INTO tablename (name, contact, address, city, cap, country) \
                    VALUES " + args_str)
except psycopg2.Error as e:
  print "Cannot execute that query", e.pgerror
  sys.exit("Leaving early the script")

我收到这个错误:

TypeError: 'dict' object does not support indexing

以下帖子没有解决我的问题:

我在 official website of psycopg2 中找到了这个,但我很难理解它的含义:

Psycopg always require positional arguments to be passed as a sequence, even when the query takes a single parameter. And remember that to make a single item tuple in Python you need a comma! See Passing parameters to SQL queries.

我确实认为我的问题与 to this 相关:


cur_psql.mogrify 像那样使用时需要位置参数,但您可以像 (%(customerName)s,%(contactName)s,%(address)s,%(city)s,%(postal_code)s,%(country)s)

那样使用 named parameters

话虽如此,与其让 python 生成大量参数,不如考虑使用 cur_psql.executemany:

cur_psql.executemany("INSERT INTO tablename (name, contact, address, city, cap, country) VALUES (%(customerName)s,%(contactName)s,%(address)s,%(city)s,%(postal_code)s,%(country)s)", cur_msql)