简体   繁体   English

在 psycopg2 中对 PostgreSQL 查询使用多个游标有什么好处?

[英]What is the advantage of using multiple cursors in psycopg2 for PostgreSQL queries?

What is the difference between using a single cursor in psycopg2 to perform all your queries against using multiple cursors.在 psycopg2 中使用单个 cursor 来执行所有针对使用多个游标的查询有什么区别。

Ie, say I do this:即,说我这样做:

import psycopg2 as pg2
con = psycopg2.connect(...)
cur = con.cursor()
cur.execute(...)
....
....
cur.execute(...)
...

and every time I wish to execute a query thereafter, I use the same cursor cur .之后每次我希望执行查询时,我都会使用相同的 cursor cur

Alternatively I could do this every time I want to query my database:或者,每次我想查询我的数据库时,我都可以这样做:

with cur as con.cursor():
    cur.execute(...)

In which case, my cursor cur would be deleted after every use.在这种情况下,我的 cursor cur将在每次使用后被删除。

Which method is better?哪种方法更好? Does one have an advantage over another?一个人比另一个人有优势吗? Is one faster than the other?一个比另一个快吗? More generally, why are multiple cursors for one connection even needed?更一般地说,为什么一个连接需要多个游标?

The two options are comparable;这两个选项具有可比性; you can always benchmark both to see if there's a meaningful difference, but psycopg2 cursors are pretty lightweight (they don't represent an actual server-side, DECLARE d cursor, unless you pass a name argument ) and I wouldn't expect any substantial slowdown from either route.您始终可以对两者进行基准测试以查看是否存在有意义的差异,但是 psycopg2 游标非常轻量级(它们不代表实际的服务器端, DECLARE d cursor, 除非您传递name参数)而且我不希望有任何实质性任一路线的减速。

The reason psycopg2 has cursors at all is twofold. psycopg2 有游标的原因是双重的。 The first is to be able to represent server-side cursors for situations where the result set is larger than memory, and can't be retrieved from the DB all at once;第一个是能够在结果集大于 memory 并且不能一次从数据库中检索到的情况下表示服务器端游标; in this case the cursor serves as the client-side interface for interacting with the server-side cursor.在这种情况下,cursor 用作与服务器端 cursor 交互的客户端接口。

The second is that psycopg2 cursors are not thread-safe;第二个是 psycopg2 游标不是线程安全的; a connection object can be freely used by any thread, but each cursor should be used by at most one thread.一个连接 object 可以被任何线程自由使用,但是每个 cursor 最多只能被一个线程使用。 Having a cursor-per-thread allows for multithreaded applications to access the DB from any thread, while sharing the same connection.每个线程都有一个游标允许多线程应用程序从任何线程访问数据库,同时共享相同的连接。

See the psycopg2 usage docs on server side cursors and thread and process safety for more details.有关更多详细信息,请参阅有关服务器端游标线程和进程安全的 psycopg2 使用文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM