nlr*_*r25 36 python sql postgresql
我有这个问题:
some_id = 1
cursor.execute('
SELECT "Indicator"."indicator"
FROM "Indicator"
WHERE "Indicator"."some_id" = %s;', some_id)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
TypeError: 'int' object does not support indexing
Run Code Online (Sandbox Code Playgroud)
some_id是一个int,但是我想选择some_id = 1的指标(或者我决定放入变量的#).
Ste*_*han 39
cursor.execute('
SELECT "Indicator"."indicator"
FROM "Indicator"
WHERE "Indicator"."some_id" = %s;', [some_id])
Run Code Online (Sandbox Code Playgroud)
这会将some_id
参数转换为可索引的列表.假设你的方法像我认为的那样工作,这应该工作.
错误正在发生,因为在该方法的某个地方,它可能试图迭代该输入,或直接索引到它.可能是这样的:some_id[0]
通过使其成为列表(或可迭代),您可以将其索引到第一个元素中.
你也可以通过这样做把它变成一个元组:(some_id,)
它具有不可变的优点.
ale*_*cxe 27
您应该将查询参数传递execute()
给元组(严格来说是可迭代的),(some_id,)
而不是some_id
:
cursor.execute('
SELECT "Indicator"."indicator"
FROM "Indicator"
WHERE "Indicator"."some_id" = %s;', (some_id,))
Run Code Online (Sandbox Code Playgroud)
您的 id 需要某种可迭代的 mogrify 才能理解输入,这是常见问题文档中的相关引用:
>>> cur.execute("INSERT INTO foo VALUES (%s)", "bar") # WRONG
>>> cur.execute("INSERT INTO foo VALUES (%s)", ("bar")) # WRONG
>>> cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct
>>> cur.execute("INSERT INTO foo VALUES (%s)", ["bar"]) # correct
Run Code Online (Sandbox Code Playgroud)
这应该有效:
some_id = 1
cursor.execute('
SELECT "Indicator"."indicator"
FROM "Indicator"
WHERE "Indicator"."some_id" = %s;', (some_id, ))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32232 次 |
最近记录: |