简体   繁体   中英

How do I alter a row in a mySQL query result?

I want to iterate through a bunch of mySQL rows in Python and, after I process each row, alter it:

cursor.execute("SELECT someNonUniqueColumn,hasBeenProccessed 
                FROM myTable WHERE hasBeenProcessed = 0")
for row in cursor:
    # use someNonUniqueColumn for something...
    ...
    # set "hasBeenProccessed" to 1

I'd like to avoid the ugliness of: - having to execute another SQL query each time I process a record, or - fill an array with the ID's of rows as I process them (Both of which would require that I add a unique key to the table)

So, is there a way to "check these off as I go"?

No, there's no way to change a row in-pace. There's a number of reasons for this, one of them is that values returned by a query may be not updatable: think counts, sums and other aggregate functions.

If you do just a very small amount of database interaction, saving IDs and issuing a compound update statement seems best.

If you issue more than 1-2 queries in your program, do yourself a favor and learn SQLAlchemy or Django ORM. Neither is completely transparent, but either will save you massive amounts of time and debugging pain.

Why not run a query after you do the changes/processing

UPDATE myTable SET hasBeenProcessed = 1 WHERE hasBeenProcessed = 0

If this is possible of course :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM