使用pymysql从服务器逐行获取行
Fetching rows one by one from server using pymysql
我有一个查询 returns 很多行,并且由于存在我需要获取的 BLOB
行,每行都很大。
我查询如下:
import pymysql
db = pymysql.connect(...)
with db.cursor() as cur:
cur.execute("select value from my_blobs")
for row in cur:
...
我天真地期望迭代 cur
而不是调用 fetchall()
会避免一次获取所有数据和 运行 过程中内存不足。但是,我看到内存在调用 cur.execute()
期间耗尽,也就是说,在我尝试通过 fetchall()
、fetchone()
或迭代 [=12] 获取结果之前=].
我的问题是,我怎样才能一个一个地得到我的斑点?我必须在应用程序中迭代并为每个 blob 进行新查询吗?那么如果在 execute()
期间查询整个数据,那么 fetchone
或迭代 cur
有什么用?
默认游标class正在缓冲数据。幸运的是有无缓冲版本:pymysql.cursors.SSCursor
。尝试 运行 db.cursor(pymysql.cursors.SSCursor)
而不是 db.cursor()
.
Unbuffered Cursor, mainly useful for queries that return a lot of data, or for connections to remote servers over a slow network.
Instead of copying every row of data into a buffer, this will fetch rows as needed. The upside of this is the client uses much less memory, and rows are returned much faster when traveling over a slow network or if the result set is very big.
我有一个查询 returns 很多行,并且由于存在我需要获取的 BLOB
行,每行都很大。
我查询如下:
import pymysql
db = pymysql.connect(...)
with db.cursor() as cur:
cur.execute("select value from my_blobs")
for row in cur:
...
我天真地期望迭代 cur
而不是调用 fetchall()
会避免一次获取所有数据和 运行 过程中内存不足。但是,我看到内存在调用 cur.execute()
期间耗尽,也就是说,在我尝试通过 fetchall()
、fetchone()
或迭代 [=12] 获取结果之前=].
我的问题是,我怎样才能一个一个地得到我的斑点?我必须在应用程序中迭代并为每个 blob 进行新查询吗?那么如果在 execute()
期间查询整个数据,那么 fetchone
或迭代 cur
有什么用?
默认游标class正在缓冲数据。幸运的是有无缓冲版本:pymysql.cursors.SSCursor
。尝试 运行 db.cursor(pymysql.cursors.SSCursor)
而不是 db.cursor()
.
Unbuffered Cursor, mainly useful for queries that return a lot of data, or for connections to remote servers over a slow network.
Instead of copying every row of data into a buffer, this will fetch rows as needed. The upside of this is the client uses much less memory, and rows are returned much faster when traveling over a slow network or if the result set is very big.