问题描述:

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?

网友答案:

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

网友答案:

You could use for like:

for row in cursor:
  ...

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

相关阅读:
Top