TypeError: 'int' object is not iterable - Python

TypeError: 'int' object is not iterable - Python

我收到以下错误:

  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)

添加逗号使其成为元组:

(id,)

完整的行是:

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

将表达式放在括号中只是 'groups' 那个表达式。正是 逗号 使某物成为元组:

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

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

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

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