Fetching some values into variables

1.1k Views Asked by At

I got this code:

cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
rows = cursor.fetchall()
for row in rows:
   print(row[0])

I'd like to have whatever it returns into some variables. How could I do it?

EDIT:

I think I'm not explaining myself properly. What I want is to have two variables with two values of the same column, not of the same row. For example:

There's two rows:

id 1, nom Natillas, listacompra 1

id 2, nom Chocolate, listacompra 1

I'd like to have two (or more) variables in order to have one variable with "Natillas" and other one with "Chocolate".

Thanks

2

There are 2 best solutions below

2
On BEST ANSWER

Using list comprehensions:

cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
rows = cursor.fetchall()
var1 = row[0][0]   # or row['nom'] if you are fetching as dict 
var2 = row[1][0]

Obviously for this to work you have to be sure query will return at least two rows.

Old answer

The iterator will return a tuple representing the row specified in the query. For example, for the query SELECT id, password FROM users the variable row will contain the id value in the first position and password in the second.

For example:

for row in rows:
    id = row[0]
    pwd = row[1]

Or, more coincise:

for row in rows:
    id, pwd = row

Unless you specify the option cursorclass=pymysql.cursors.DictCursor when defining the connection, in this case it will return a dictionary:

for row in rows:
    id = row['id']
    pwd = row['password']
1
On
rows = cursor.fetchall()
for row in rows:
   print(row['<key of table field>'])