cx_Oracle:如何迭代结果集? [英] cx_Oracle: How do I iterate over a result set?
问题描述
有几种方法可以遍历结果集.两者的权衡是什么?
There are several ways to iterate over a result set. What are the tradeoff of each?
推荐答案
规范的方法是使用内置的游标迭代器.
The canonical way is to use the built-in cursor iterator.
curs.execute('select * from people')
for row in curs:
print row
您可以使用fetchall()
一次获取所有行.
You can use fetchall()
to get all rows at once.
for row in curs.fetchall():
print row
使用它来创建包含返回值的Python列表可能会很方便:
It can be convenient to use this to create a Python list containing the values returned:
curs.execute('select first_name from people')
names = [row[0] for row in curs.fetchall()]
这对于较小的结果集很有用,但是如果结果集很大,可能会有不良的副作用.
This can be useful for smaller result sets, but can have bad side effects if the result set is large.
-
您必须等待整个结果集返回到 您的客户流程.
You have to wait for the entire result set to be returned to your client process.
您可能会吞噬客户端中的大量内存以进行保存 内置列表.
You may eat up a lot of memory in your client to hold the built-up list.
Python可能需要一段时间才能构造和解构 列出您将要立即丢弃的内容.
It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways.
如果您知道结果集中将返回单行,则可以调用fetchone()
来获取单行.
If you know there's a single row being returned in the result set you can call fetchone()
to get the single row.
curs.execute('select max(x) from t')
maxValue = curs.fetchone()[0]
最后,您可以循环遍历结果集,一次获取一行.通常,与使用迭代器相比,这样做没有什么特别的优势.
Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator.
row = curs.fetchone()
while row:
print row
row = curs.fetchone()
这篇关于cx_Oracle:如何迭代结果集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!