类型错误:';int';对象不可编辑-Python

类型错误:';int';对象不可编辑-Python,python,mysql,python-2.7,mysql-python,Python,Mysql,Python 2.7,Mysql 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,

我得到了以下错误:

  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

您需要指定
游标。执行一个元组,但只指定一个整数:

(id)
添加逗号使其成为元组:

(id,)
那么,完整的行将是:

cursor.execute("""select test_id from test_logs where id = %s """, (id,))
把一个表达式放在括号里,只是“分组”了那个表达式。正是逗号使某物成为元组:

>>> (42)
42
>>> (42,)
(42,)
任何iterable都可以,因此您也可以使用
[…]
括号:

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

基本上,当您在查询中传递一个参数时,它不会变成一个iterable,因为它在括号中。
为了使其可移植,您需要将其设置为列表或元组等形式。因此,您可以在末尾(1,)添加逗号,也可以将其作为列表[1]。

这应该是
光标。执行(…,(id,)
-注意后面的逗号,这使其成为元组。@JonSharpe您能解释清楚吗?Martijn已经有了!请参见,例如,你好,像这样尝试[id]处理问题非常烦人this@briankip:为什么很烦人?它的基本语法;编程语言总是在不同的上下文中使用相同的符号表示不同的含义。逗号用于元组中以及将不同参数分隔为函数签名时,或用于分隔类定义中的基类,或用于分隔调用表达式中的参数或列表中的值等。因为有时需要区分元组和其他含义,您需要在元组周围使用括号来消除歧义。但仍然是逗号使某些东西成为元组。@briankip:这不是MySQLdb特有的。它在所有Python数据库适配器中都很常见;它们都遵循@briankip:它像一个带参数的普通函数一样工作。
cursor.execute()
函数的第二个参数是查询参数参数。它是一个包含所有参数值的单个对象。如果只有一个参数,那么是的,这是一个单元素元组。对于2个或更多对象,可以在该对象中获得2个或更多值。它可以是元组或列表。@briankip:如果使用命名参数,则使用映射(字典),参数名称作为键。