python - 如何做 while() "pythonic way"

标签 python

我想这样做:

from django.db import connection

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

我明白了:

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

这样做的“pythonic”方式是什么?

最佳答案

您根本不必使用 while 循环,因为游标是可迭代的:

for row in cursor:
    print(row)

来自 Django documentation 的“连接和游标”部分:

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

来自提到的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

关于python - 如何做 while() "pythonic way",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32199150/

相关文章:

Python - 如何使用 DateTime 重命名文本文件

python:如何通过ssh远程运行脚本

python - 单击 'submit' 时如何获取下载的 pdf 文件,这也会将我重定向到新页面

python - Pandas If Else 条件对多列

python - 如何通过在 Python 中调用相同的字典值每次都返回新的对象?

Canvas 内的 Python Tkinter Canvas

python - Opencv 上的线性倒置图像

Python 3.3 pygame 1.9.2a0(64 位)图形窗口显示第一个图像但随后卡住

python - 如何使用 FFT 卷积执行形态侵 eclipse

python - CUDA 9.0 和 pycuda,错误 :CompileError: nvcc compilation . .. kernel.cu 失败