我正在使用python的sqlite3模块.
我想遍历表中的行,直到没有剩下的行.我想一次做一个而不是使用fetchall因为表非常大.我读了python sqlite3文档,当光标选择中没有任何行时curs.fetchone()返回None.
所以我有想法在while fetchone():循环中运行我的代码,在循环中fetchone()发生'实际' 调用,如下所示:
while c.fetchone():
row = c.fetchone()
print(foo(row))
Run Code Online (Sandbox Code Playgroud)
我不知道这个循环是否实际上是在while语句中获取一次,而是在body中获取一次,或者它是否仅在正文中.哪一个?
它会执行fetchone两次,所以这不是一个好主意.由于sqlite3.Cursor是可迭代的,你可以这样做:
for row in c:
print(foo(row))
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用无限循环并批量获取数据fetchmany:
# Lets take 1000 rows at the time
batch_size = 1000
while True:
rows = c.fetchmany(batch_size)
if not rows: break
for row in rows:
print(foo(row))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3432 次 |
| 最近记录: |