【问题标题】:TypeError: 'int' object does not support indexingTypeError:“int”对象不支持索引
【发布时间】:2013-08-23 03:21:55
【问题描述】:

我有这个问题:

some_id = 1

cursor.execute('
    SELECT "Indicator"."indicator" 
    FROM "Indicator" 
    WHERE "Indicator"."some_id" =   %s;', some_id)

我收到以下错误:

TypeError: 'int' object does not support indexing

some_id 是一个 int 但我想选择 some_id = 1 的指标(或我决定放入变量中的任何 #)。

【问题讨论】:

    标签: python sql postgresql


    【解决方案1】:
    cursor.execute('
        SELECT "Indicator"."indicator" 
        FROM "Indicator" 
        WHERE "Indicator"."some_id" =   %s;', [some_id])
    

    这会将some_id 参数转换为可索引的列表。假设你的方法像我认为的那样有效,这应该有效。

    发生错误是因为在该方法的某处,它可能试图迭代该输入,或直接对其进行索引。可能是这样的:some_id[0]

    通过使其成为列表(或可迭代),您可以允许它像这样索引到第一个元素。

    您也可以通过这样做将其变成一个元组:(some_id,),它具有不可变的优点。

    【讨论】:

      【解决方案2】:

      您应该将查询参数作为元组(严格来说是可迭代的)传递给execute()(some_id,) 而不是some_id

      cursor.execute('
          SELECT "Indicator"."indicator" 
          FROM "Indicator" 
          WHERE "Indicator"."some_id" =   %s;', (some_id,))
      

      【讨论】:

      • 逗号让一切变得不同。没有意识到单个项目元组不会变成没有逗号的元组......
      【解决方案3】:

      您的 id 需要是某种可迭代的 mogrify 才能理解输入,这是来自 frequently asked questions documentation 的相关引用:

      >>> 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
      

      这应该可行:

      some_id = 1
      
      cursor.execute('
          SELECT "Indicator"."indicator" 
          FROM "Indicator" 
          WHERE "Indicator"."some_id" =   %s;', (some_id, ))
      

      【讨论】:

        【解决方案4】:

        使用 Django 时出现轻微类似错误:

        TypeError: 'RelatedManager' object does not support indexing
        

        这行不通

        mystery_obj[0].id
        

        这行得通:

        mystery_obj.all()[0].id
        

        基本上,错误读取为Some type xyz doesn't have an __ iter __ or __next__ or next function, so it's not next(), or itsnot[indexable], or iter(itsnot),在这种情况下cursor.execute 的参数需要实现迭代,最常见的是ListTuple,或者不太常见的是Array,或者一些自定义迭代器实施。

        在这种特定情况下,当经典字符串插值填充%s%d%b 字符串格式化程序时会发生错误。

        相关:

        【讨论】:

          猜你喜欢
          • 2018-01-07
          • 2013-06-23
          • 2019-04-18
          • 2016-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多