python - 使用 pymysql 从服务器中逐行获取行

标签 python pymysql

我有一个查询返回许多行,并且由于存在需要提取的 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() 或通过迭代 cur

我的问题是,如何才能一一获取我的 Blob ?我是否必须在应用程序中进行迭代并对每个 blob 进行新查询?那么如果在 execute() 期间查询整个数据,那么 fetchone 或迭代 cur 有什么用呢?

最佳答案

默认游标类是缓冲数据。幸运的是,有一个无缓冲版本:pymysql.cursors.SSCursor。尝试运行 db.cursor(pymysql.cursors.SSCursor) 而不是 db.cursor()。

来自API reference for SSCursor :

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.

关于python - 使用 pymysql 从服务器中逐行获取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405752/

相关文章:

python - pyzmq 发布者可以从类实例进行操作吗?

python - GAE Python - Cron 作业未在目标模块上执行

python - 从名称中带点的文件夹导入 - Python

python-3.x - python3 sqlalchemy pymysql 连接字符串

python - 将行从一个数据库复制到另一个数据库并更改一些值

使用init.d运行的Python程序不写入数据

python - 从 Python 查找 MacOSX 版本

python - 数组到二叉搜索树

python - 多份打印输出,仅打印其中一份

mysql - 如何连接到 python3 中的 AWS mysql 数据库?