【问题标题】:TypeError: 'int' object is not iterable - PythonTypeError:'int'对象不可迭代 - Python
【发布时间】:2015-04-06 14:01:06
【问题描述】:

我收到以下错误:

  File "/home/ec2-user/test/test_stats.py", line 43, in get_test_ids_for_id
    cursor.execute("""select test_id from test_logs where id = %s """, (id))
  File "/home/ec2-user/.etl/lib/python2.7/site-packages/MySQLdb/cursors.py", line 187, in execute
    query = query % tuple([db.literal(item) for item in args])
TypeError: 'int' object is not iterable

这是我遇到问题的代码部分:

def get_test_ids_for_id(prod_mysql_conn, id):
    cursor = prod_mysql_conn.cursor()
    cursor.execute("""select test_id from test_logs where id = %s """, (id))
    rows = cursor.fetchall()
    test_ids = []
    for row in rows:
      test_ids.append(row[0])
    return test_ids

【问题讨论】:

  • 应该是cursor.execute(..., (id,)) - 注意尾随的逗号,这使它成为一个元组。
  • @jonrsharpe 你能解释清楚吗?
  • Martijn 已经有了!参见例如stackoverflow.com/q/22460082/3001761
  • 你好试试这样[id]

标签: python mysql python-2.7 mysql-python


【解决方案1】:

你需要给cursor.execute一个元组,但你只给了它一个整数:

(id)

添加一个逗号以使其成为一个元组:

(id,)

那么整行应该是:

cursor.execute("""select test_id from test_logs where id = %s """, (id,))

将表达式放在括号中只是“组合”该一个表达式。正是 逗号 使某些东西成为元组:

>>> (42)
42
>>> (42,)
(42,)

任何可迭代的都可以,所以你也可以使用[...] 括号:

cursor.execute("""select test_id from test_logs where id = %s """, [id])

【讨论】:

  • 处理这个很烦人
  • @briankip:为什么这很烦人?这是基本语法;编程语言总是在不同的上下文中使用相同的符号来表示不同的含义。逗号用于元组中,用于分隔函数签名的不同参数,或用于分隔类定义中的基类,或用于分隔调用表达式中的参数或列表中的值等。因为有时您需要区分在元组和其他含义之间,您需要在元组周围使用括号来消除歧义。但它仍然是使某些东西成为元组的逗号。
  • @briankip:这不是 MySQLdb 特定的。它在所有 Python 数据库适配器中都很常见;他们都关注Python Database API Specification
  • @briankip:它的工作方式就像一个带参数的普通函数。 cursor.execute() 函数的第二个参数是查询参数参数。它是一个包含所有参数值的对象。如果你只有一个参数,那么是的,那是一个单元素元组。对于 2 或更多,您将在该对象中获得 2 或更多值。它可以是元组或列表。
  • @briankip:如果您使用 named 参数,那么您使用映射(字典),以参数名称作为键。
【解决方案2】:

基本上,当您在查询中传递参数时,它不会变成可迭代的,因为它在括号中。 为了使其可迭代,您需要以列表或元组之类的形式制作它。所以您可以在末尾添加逗号 (1,) 或将其设为列表 [1]。

【讨论】:

    猜你喜欢
    • 2013-10-31
    • 2016-02-24
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    相关资源
    最近更新 更多