TypeError:’int’对象不可迭代 – 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.exe一个元组,但你只给它一个整数:

(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])

dawei

【声明】:淮南站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。