重用游标与创建新游标有何权衡?

发布于 2024-08-17 11:52:40 字数 528 浏览 6 评论 0原文

在cx_Oracle(或一般的Oracle)中,是否可以为每个查询分配一个游标,或者在多个查询之间重用一个游标。

def getSomeData(curs):         # case 1: pass in a cursor, which is generally
    curs.execute('select ...') #         reused across queries
    return curs.fetchall()

def getSomeData(conn):         # case 2: pass in a connection,allocate
    curs=conn.cursor()         #         a cursor for this query
    curs.execute('select ...')
    return curs.fetchall()

当然,这两种方法返回相同的数据。

两种方法之间的权衡是什么?效率特别高还是低?在许多查询中重用游标是否存在潜在的陷阱?

In cx_Oracle (or Oracle in general), is it possible to allocate a cursor for each query, or to reuse a cursor across several queries.

def getSomeData(curs):         # case 1: pass in a cursor, which is generally
    curs.execute('select ...') #         reused across queries
    return curs.fetchall()

def getSomeData(conn):         # case 2: pass in a connection,allocate
    curs=conn.cursor()         #         a cursor for this query
    curs.execute('select ...')
    return curs.fetchall()

Of course, both approaches return the same data.

What are the tradeoffs between the two approaches? Is one particularly more or less efficient? Are there any potential pitfalls to reusing a cursor over many queries?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最初的梦 2024-08-24 11:52:40

您可以随意重复使用 cx_Oracle 游标,没有问题。如果您在很短的时间内执行数千个小型查询,您可能会发现通过重新使用游标可以稍微提高性能,但我对此表示怀疑。

我有时会创建新的游标,有时会重新使用现有的游标,具体取决于它是否使代码更易于阅读和理解。

例如,如果我有多个需要访问数据库的过程,我可能会传递一个 Oracle 连接对象,或者在该连接上创建的游标。

任何能让你的代码更具可读性和更易于维护的东西都是我所追求的。

You can re-use a cx_Oracle cursor as much as you like, no problem. If you're executing thousands of small queries in a small space of time, you might see a slight performance improvement by re-using the cursor, but I doubt it.

I will sometimes create new cursors, and other times re-use an existing one, depending on whether it makes the code easier to read and understand.

For example, if I have a variety of procedures that need to access the database, I might pass an Oracle connection object around, or a cursor created on that connection.

Whatever makes your code more readable and easier to maintain is what I'd go for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文