0

I am trying to loop through a series of rows in an SQLite DB using the following code:

cur.execute("SELECT * FROM SmallBodyDB")
count = 0
for row in cur:

    - Some code -

    conn.commit()
    count = count + 1

The code in - some code - works fine, but will only look at the first line. Basically, it will only loop once. I need it to loop through the whole DB.

Any ideas why?

Cheers

5
  • What's the point of your count variable? Commented Jun 4, 2020 at 1:06
  • @JamesMcPherson I am just using it to count up how many loops have been iterated. Commented Jun 4, 2020 at 1:09
  • 1
    Do you need it though? Assuming that you do, then try something like for count, row in enumerate(cur.fetchall()): which gives you the count for pretty much no extra cost Commented Jun 4, 2020 at 1:12
  • That is a good idea, thank you. However, when I just ran it on a DB with 21 lines of data in it, it returned a value of 20. Any idea why? Commented Jun 4, 2020 at 1:16
  • 1
    Enumerators start at 0 :-) Commented Jun 4, 2020 at 1:19

1 Answer 1

2

You need to fetch all the rows from the cursor:

for row in cur.fetchall():
    ... per-row operations
    conn.commit()

Though that will, of course, slow you down since you're committing the implicit transaction for every row. You could probably (since this is sqlite) run conn.commit() after the conclusion of your for loop.

Sign up to request clarification or add additional context in comments.

2 Comments

That worked. Thank you. Regarding the comment about conn.commit(), what is the ballpark limit of the number of lines that can be looped through before it has to be run, supposing it is being run on a good laptop (32GB RAM)? 100s, 1000s, or 10,000s?
That depends entirely on your confidence :-) I was writing a pipeline recently which had to update an Oracle DB, and my confidence limit was around 100,000 rows per commit.

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.