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?

6
  • Python will add an assignment expression in Python 3.8. Before that, assignments were always statements. If you don't have that, then item = cursor.fetchone(); while item: ....; item = cursor.fetchone() Commented Sep 10, 2019 at 19:43
  • what's your DB engine? Commented Sep 10, 2019 at 19:44
  • As an aside, this was a highly controversial addition to the language. Apparently, the furor over PEP 572's adoption was so great that it was a main motivation behind Guido van Rossum stepping down as BDFL. lwn.net/Articles/759654 Commented Sep 10, 2019 at 19:46
  • @RomanPerekhrest good question, as some DB adaptor api's support direct iteration over the cursor to obtain results row-by-row. Commented Sep 10, 2019 at 19:46
  • It would be wise to add a respective DB engine name to a list of tags in your case Commented Sep 10, 2019 at 19:48

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.