我正在处理这段代码,python 2.6.6,旧版本,因为我必须在安装了基础存储库(稳定)且没有权限的 Linux 服务器(可能是 centOS 6 或 Debian)上执行此脚本安装这些存储库中没有的软件。
此片段注意从具有特定架构(db 结构)的数据库(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 当你像这样使用它时需要位置参数,但你可以使用 named parameters例如 (%(customerName)s,%(contactName)s,%(address)s,%(city)s,%(postal_code)s,%(country)s)
话虽如此,不要让 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)
关于python - 类型错误 : 'dict' object does not support indexing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145186/