1

What would be the closest pattern to doing the above in python?

while (item=self.cursor.fetchone()):
    print item['id']

Basically, I'd like to get the result of a single database-row. What would be the most direct way to do this, or do I need to have some generic loop like while 1?

David542
  • 101,766
  • 154
  • 423
  • 727

1 Answers1

1

There's a comprehensive section on MySQLCursor.fetchone() doc page:

The following example shows two equivalent ways to process a query result. The first uses fetchone() in a while loop, the second uses the cursor as an iterator:

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
    print(row)
    row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
    print(row)
RomanPerekhrest
  • 75,918
  • 4
  • 51
  • 91
  • Got it -- thanks for this very clear example and the two options. The second option is pretty neat, I had never seen that style done before. – David542 Sep 10 '19 at 20:01