python - 类型错误 : 'dict' object does not support indexing

标签 python dictionary psycopg2 mysql-python python-2.6

我正在处理这段代码,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/

相关文章:

python - 如何将退格键应用于字符串

Ruby Map 方法编辑原始数组?

python - 使用 psycopg2 将 PostgreSQL UUID 数组作为列表返回

python日志记录模块没有向文件写入任何内容

python - Django ModelChoiceField 查询集的自定义顺序

Pythonbrew 无法构建 python 2.6

python - 从变量名或字符串创建列表或字典

python - 在 Python 中存储集合数据的最佳方式是什么?

postgresql - psycopg 2's "execute()”是否提供足够的 SQL 注入(inject)预防?

python - 如何在Python中打印查询结果,包括列名