当我迭代游标时 psycopg2 在做什么?
What's psycopg2 doing when I iterate a cursor?
我想了解这段代码在幕后做了什么:
import psycopg2
c = psycopg2.connect('db=some_db user=me').cursor()
c.execute('select * from some_table')
for row in c:
pass
根据 PEP 249 my understanding was that this was repeatedly calling Cursor.next()
which is the equivalent of calling Cursor.fetchone()
. However, the psycopg2
docs say the following:
When a database query is executed, the Psycopg cursor usually fetches
all the records returned by the backend, transferring them to the
client process.
所以我很困惑 -- 当我 运行 上面的代码时,它是将结果存储在服务器上并一个一个地获取它们,还是一次把所有东西都带过来?
这取决于您如何配置psycopg2
。参见 itersize
and server side cursors。
默认情况下,它会将所有行提取到客户端内存中,然后使用游标遍历提取的行。但是根据上述文档,您可以改为从 server-side 游标配置批量提取。
我想了解这段代码在幕后做了什么:
import psycopg2
c = psycopg2.connect('db=some_db user=me').cursor()
c.execute('select * from some_table')
for row in c:
pass
根据 PEP 249 my understanding was that this was repeatedly calling Cursor.next()
which is the equivalent of calling Cursor.fetchone()
. However, the psycopg2
docs say the following:
When a database query is executed, the Psycopg cursor usually fetches all the records returned by the backend, transferring them to the client process.
所以我很困惑 -- 当我 运行 上面的代码时,它是将结果存储在服务器上并一个一个地获取它们,还是一次把所有东西都带过来?
这取决于您如何配置psycopg2
。参见 itersize
and server side cursors。
默认情况下,它会将所有行提取到客户端内存中,然后使用游标遍历提取的行。但是根据上述文档,您可以改为从 server-side 游标配置批量提取。