Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do while() the "pythonic way"

Tags:

python

I want to do this:

from django.db import connection

cursor = connection.cursor()
cursor.execute("PRAGMA table_info(ventegroupee)")
while row = cursor.fetchone():
    print(row)

I get this:

  File "<input>", line 1
    while row = cursor.fetchone():
              ^
SyntaxError: invalid syntax

What is the "pythonic" way of doing this?

like image 259
Olivier Pons Avatar asked Dec 09 '22 01:12

Olivier Pons


2 Answers

You don't have to use while loop at all, because cursors are iterable:

for row in cursor:
    print(row)

From the "Connections and cursors" section of Django documentation:

connection and cursor mostly implement the standard Python DB-API described in PEP 249 — except when it comes to transaction handling.

From the mentioned PEP 249:

Cursor.next()

Return the next row from the currently executing SQL statement using the same semantics as .fetchone()

Cursor.__iter__()

Return self to make cursors compatible to the iteration protocol

like image 173
vaultah Avatar answered Dec 24 '22 07:12

vaultah


You could use for like:

for row in cursor:
  ...

here you coul find a good tutorial about for loop in python:

like image 35
teoreda Avatar answered Dec 24 '22 09:12

teoreda