cx_Oracle:如何迭代结果集?
有多种方法可以迭代结果集。 各自的权衡是什么?
There are several ways to iterate over a result set. What are the tradeoff of each?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
有多种方法可以迭代结果集。 各自的权衡是什么?
There are several ways to iterate over a result set. What are the tradeoff of each?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
还有 psyco-pg 似乎是这样做的......根据我的收集,它似乎创建了类似字典的行代理来将键查找映射到查询返回的内存块中。 在这种情况下,获取整个答案并在行上使用类似的代理工厂似乎是有用的想法。 但仔细想想,它感觉更像是 Lua,而不是 Python。
此外,这应该适用于所有 PEP-249 DBAPI2.0 接口,不仅仅是 Oracle,或者您的意思只是使用 Oracle最快?
There's also the way
psyco-pg
seems to do it... From what I gather, it seems to create dictionary-like row-proxies to map key lookup into the memory block returned by the query. In that case, fetching the whole answer and working with a similar proxy-factory over the rows seems like useful idea. Come to think of it though, it feels more like Lua than Python.Also, this should be applicable to all PEP-249 DBAPI2.0 interfaces, not just Oracle, or did you mean just fastest using Oracle?
我的首选方法是游标迭代器,但首先设置游标的 arraysize 属性。
在此示例中,cx_Oracle 将一次从 Oracle 256 行中获取行,从而减少需要执行的网络往返次数
My preferred way is the cursor iterator, but setting first the arraysize property of the cursor.
In this example, cx_Oracle will fetch rows from Oracle 256 rows at a time, reducing the number of network round trips that need to be performed
规范的方法是使用内置的游标迭代器。
您可以使用 fetchall() 一次获取所有行。
使用它可以很方便地创建包含返回值的 Python 列表:
这对于较小的结果集很有用,但如果结果集很大,可能会产生严重的副作用。
必须等待整个结果集返回
您的客户端进程。
您可能会占用客户端的大量内存来保存
构建列表。
Python 可能需要一段时间来构造和解构
无论如何你都会立即丢弃的列表。
如果您知道结果集中返回了单行,则可以调用 fetchone() 来获取单行。
最后,您可以循环遍历结果集,一次获取一行。 一般来说,与使用迭代器相比,这样做没有特别的优势。
The canonical way is to use the built-in cursor iterator.
You can use
fetchall()
to get all rows at once.It can be convenient to use this to create a Python list containing the values returned:
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.
It may take a while for Python to construct and deconstruct the
list which you are going to immediately discard anyways.
If you know there's a single row being returned in the result set you can call
fetchone()
to get the single row.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.