2

I have an sqlite query that looks like this:

db_rows = db_cursor.execute(
    "SELECT * FROM my_table"
)

# check1
for row in db_rows:
    print(row)

# check2
for row in db_rows:
    print(row)

What happens is that the first for loop outputs all the rows, and the second does not output anythng at all which I find strange. Why is that? Is there a way for me to re-use db_rows multiple times? Perhaps this is a bug?

I need this because I have some nested code (for's and if's) which is supposed to re-use db_rows and believe it should be faster to just re-use db_rows that should be already in memory instead of executing the query again and again for each itteration of an inner loop.

Thank you.

2 Answers 2

4

... it should be faster to just re-use db_rows that should be already in memory ...

Except that it's not in memory; it's being pulled from the database one row at a time. Convert to a list if you want to pull the results into memory.

row_list = list(db_rows)

for row in row_list:
   ...
Sign up to request clarification or add additional context in comments.

Comments

3

The returned object is an iterator. The first loop consumes the iterator. The second one gets it already exhausted. If you want to retain the whole result, do this:

rows = list(db_rows)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.