Celeritas
Celeritas

Reputation: 15053

Why is `for...in` returning a tuple when trying to iterate through rows returned by query?

I select 1 column from a table in a database. I want to iterate through each of the results. Why is it when I do this it’s a tuple instead of a single value?

con = psycopg2.connect(…)
cur = con.cursor()
stmt = "SELECT DISTINCT inventory_pkg FROM {}.{} WHERE inventory_pkg IS NOT NULL;".format(schema, tableName)
cur.execute(stmt)
con.commit()
referenced = cur.fetchall()
for destTbl in referenced:#why is destTbl a single element tuple? 
    print('destTbl: '+str(referenced))
    stmt = "SELECT attr_name, attr_rule FROM {}.{} WHERE ppm_table_name = {};".format(schema, tableName, destTbl)#this fails because the where clause gets messed up because ‘destTbl’ has a comma after it
    cur.execute(stmt)

Upvotes: 0

Views: 168

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122312

Because you are getting rows from your database, and the API is being consistent.

If your query asked for * columns, or a specific number of columns that is greater than 1, you'd also need a tuple or list to hold those columns for each row.

In other words, just because you only have one column in this query doesn't mean the API suddenly will change what kind of object it returns to model a row.

Simply always treat a row as a sequence and use indexing or tuple assignment to get a specific value out. Use:

inventory_pkg = destTbl[0]

or

inventory_pkg, = destTbl

for example.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599630

Because that's what the db api does: always returns a tuple for each row in the result.

It's pretty simple to refer to destTbl[0] wherever you need to.

Upvotes: 4

Related Questions