我收到以下错误:
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])