14

I have a MSQL db and I need to iterate through a table and perform an action once a WHERE clause is met. Then once it reaches the end of the table, return to the top and start over.

Currently I have

cursor = database.cursor()    
cursor.execute("SELECT user_id FROM round WHERE state == -1 AND state = 2")  
round_id = cursor.fetchone()

if round != 5
   ...do stuff

in a loop but this obviously only keeps looping the first entry. I guess you need to use the for in function to read through the table, but I'm not sure exactly how to do this using mysqldb?

4

2 回答 2

17

Once you have results in the cursor, you can iterate right in it.

cursor = database.cursor()    
cursor.execute("SELECT user_id FROM round WHERE state == -1 AND state = 2")  
for round in cursor:
  if round[0] != 5
    ...do stuff
于 2015-12-11T17:14:55.633 回答
9

This will set the cursor at the beginning of the result set and tell you how many rows it got back (I went back and forth on this one, but this is the most authoritative documentation I have found, older Python MySQLdb lib returned rowcount on execute, but Python Database API Specification v2.0 does not, this should be the most compatible)

cursor.execute("SELECT user_id FROM round WHERE state = -1 OR state = 2")
numrows = cursor.rowcount

Will tell you how many Rows you got in return

for x in xrange(0,numrows):
  row = cursor.fetchone()
  print row[0], "-->", row[1]

Will iterate over each row (no need to enumerate x with range)

于 2013-03-13T22:05:50.270 回答