G
G
gonchar0ff2021-04-10 14:13:32
Python
gonchar0ff, 2021-04-10 14:13:32

How to display all data from a table using Python (SQLite)?

Hello everybody!
Relatively speaking, there is a database that looks like this:
ID product_name price shop
1 Bread 23 At home
2 Milk 50 Eight
3 Kefir 30 Petrovich

's I'm trying to write a function that will display ID and product_name

def get_all(): 
    cur.execute('SELECT * FROM product_table')
    rows = cur.fetchall()
    for row in rows:
        name = str(row[1])
        id = str(row[0])
        return name, id

But it only outputs the first line: "1 Bread". If instead of
return name, id
writing
print(name,id)
, it displays all the lines, but the last line is None, which is logical in theory, because the function does not contain return, which means it returns None by default.

What am I missing?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-04-10
@gonchar0ff

then outputs all lines but the last line is None

What's the last one? If you do print(get_all())something
Either return fetchall() and already work with it (then it’s not clear why the function exists), or immediately form the necessary data in the desired variant and return it, something like this:
def get_all():
    records = []
    cur.execute('SELECT * FROM stocks')
    rows = cur.fetchall()
    for row in rows:
        records.append({'name': str(row[1]), 'id': str(row[0])})
    return records

Y
Yupiter7575, 2021-04-10
@yupiter7575

When return is called, the function stops and returns a value. return in a loop is a sin

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question