1

I am trying to increment row in MySQL database like this

rows = cursor.fetchall()

i = 0
for row in rows:
    cursor.execute("UPDATE Table SET order = %s WHERE name = 'JAMES'", (i,))
    db.commit()
    i += 1

But at the end order for all of the items is 19, and the length of rows is 20. How can I have it go form 0 to 19, I though if I commit() after each loop this would be solved?

Thanks

6
  • Without where clause, the UPDATE statement will update all records. Commented Dec 16, 2015 at 7:05
  • @falsetru its there ill add it to the question I just left it out by accident Commented Dec 16, 2015 at 7:05
  • Is it always 'JAMES'? Then, the same records will be updated multiple times. Commented Dec 16, 2015 at 7:06
  • @falsetru why does it matter what the WHERE clause is? No it is not always james, it is getting a different row every time Commented Dec 16, 2015 at 7:07
  • 1
    Do you mean something like this? cursor.execute("UPDATE Table SET order = %s WHERE name = %s", (i, row.name)). WHERE clause matters. Commented Dec 16, 2015 at 7:09

1 Answer 1

2

Maybe you meant something like this (WHERE clause change for rows):

rows = cursor.fetchall()
for i, row in enumerate(rows):
    cursor.execute("UPDATE Table SET order = %s WHERE name = %s", (i, row.name))
    db.commit()

Otherwise, order fields or one record is updated multiple times.

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

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.