Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MySQLdb iterate through table

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?

like image 516
DavidJB Avatar asked Mar 13 '13 21:03

DavidJB


People also ask

How do I query a MySQL database in python?

To query data in a MySQL database from Python, you need to do the following steps: Connect to the MySQL Database, you get a MySQLConnection object. Instantiate a MySQLCursor object from the the MySQLConnection object. Use the cursor to execute a query by calling its execute() method.


1 Answers

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
like image 99
Dvd Avins Avatar answered Sep 24 '22 11:09

Dvd Avins