Runner Bean
Runner Bean

Reputation: 5165

sqlite python, nested loop stops main loop

import  sqlite3
conn = sqlite3.connect('food.db')
c = conn.cursor()

c.execute('''CREATE TABLE IF NOT EXISTS nutritional_values
                (item, calories, total fat, protein)''')
items = [       ('Broccoli Chinese',    22,     0.7,    1.1),
                ('chia seeds',          490,    30.8,   15.6),
                ('blueberries',         57,     0.3,    0.7),]
c.executemany('INSERT INTO nutritional_values VALUES (?,?,?,?)',items)


c.execute('''CREATE TABLE IF NOT EXISTS food_consumption
                (date, item, amount)''')
c.execute('DELETE FROM food_consumption')
consumed = [    ('24/8/2019', 'Broccoli Chinese',    1.5),
                ('24/8/2019', 'chia seeds',          0.35),
                ('24/8/2019', 'blueberries',         0.4),]
c.executemany('INSERT INTO food_consumption VALUES (?,?,?)',consumed)

conn.commit()
conn.close()

If I run:

for row in c.execute('SELECT * FROM food_consumption'):
    print(row[1])

as expected I get:

Broccoli Chinese
chia seeds
blueberries

but if I run:

for row in c.execute('SELECT * FROM food_consumption'):
    print(row[1])
    for number in c.execute('SELECT calories FROM nutritional_values WHERE item=(?)', (row[1],)):
        print(number)

I get:

Broccoli Chinese
(22,)

So it no longer loops over all the rows in the table 'food_consumption', how do I get it to loop over all rows?

Upvotes: 3

Views: 72

Answers (2)

ruohola
ruohola

Reputation: 24038

The cursor can only hold results of one query at a time, you need to save the results of the first query to a variable:

first = c.execute('SELECT * FROM food_consumption').fetchall()

for row in first:
    print(row[1])
    for number in c.execute('SELECT calories FROM nutritional_values WHERE item=(?)', (row[1],)):
        print(number)

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

I don't know exactly why your current approach is not working, but in any case it is a bad design pattern and you should instead by doing a join between the two tables, handling the relationship on the database side:

sql = """SELECT nv.item, nv.calories
         FROM nutritional_values nv
         INNER JOIN food_consumption fc
             ON nv.item = fc.item"""

for row in c.execute(sql):
    print(row[1])

Note that this is the preferred way to handle your problem, because it avoids loading an entire result set into Python's memory.

Upvotes: 1

Related Questions