Brisi
Brisi

Reputation: 1831

TypeError: 'int' object is not iterable - Python

I got the following error:

  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

Here's the section of my code I'm having trouble with:

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

Upvotes: 8

Views: 17539

Answers (2)

chirag mathur
chirag mathur

Reputation: 1

Basically what is happening is when you are passing a argument in query it is not becoming an iterable because it is coming in bracket. In order to make it iterable you need to make it in that form like list or tuple. Soo you can either add comma at the end (1,) or make it a list [1].

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125318

You need to give cursor.execute a tuple, but you only gave it one integer:

(id)

Add a comma to make that a tuple:

(id,)

The full line then'd be:

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

Putting an expressione in parentheses just 'groups' that one expression. It is the comma that makes something a tuple:

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

Any iterable will do really, so you could also use [...] brackets:

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

Upvotes: 26

Related Questions