今天我和一些同事讨论了Python的db-api中fetchone、fetchmany和fetchall的区别。
虽然每个API的具体实现可能会影响它们的使用场景,但总的来说,fetchone、fetchmany和fetchall分别适合哪些使用场景呢?
换句话说,以下三个方法是否等价?如果不是,其中有一个优于其他方法吗?在哪些情况下使用?
cursor.execute("SELECT id, name FROM `table`")
for i in xrange(cursor.rowcount):
id, name = cursor.fetchone()
print id, name
cursor.execute("SELECT id, name FROM `table`")
result = cursor.fetchmany()
while result:
for id, name in result:
print id, name
result = cursor.fetchmany()
cursor.execute("SELECT id, name FROM `table`")
for id, name in cursor.fetchall():
print id, name
LIMIT
,那么fetchone
和fetchmany
的目的是什么?实际上,如果您选择了没有限制的查询,您将获得整个表。如果我仍然只使用fetchone
,这是否意味着大量行从服务器传输到客户端而没有任何理由?在这种情况下,当始终更有效的是使用LIMIT 1
时,为什么要使用fetchone
? - CMCDragonkai