SQLAlchemy在选择语句中占用过多内存

11 投票
1 回答
5604 浏览
提问于 2025-04-16 04:04

根据SQLAlchemy的说法,选择语句在for循环中被当作可迭代对象来处理。这意味着,即使一个选择语句会返回很多行数据,它也不会占用过多的内存。

我发现,在一个MySQL表上运行以下语句:

for row in my_connections.execute(MyTable.__table__.select()):
    yield row

似乎并没有遵循这个规则,因为我在还没得到第一行数据之前,就已经耗尽了可用内存,导致系统开始变得很慢。我到底哪里做错了呢?

1 个回答

14

基本上,MySQLdb 的游标会一次性从服务器获取所有查询结果。这可能会消耗大量的内存和时间。如果你想进行一个很大的查询,并且希望逐条从服务器获取结果,可以使用MySQLdb.cursors.SSCursor

因此,在创建engine时,可以尝试传入 connect_args={'cursorclass': MySQLdb.cursors.SSCursor}

   from sqlalchemy import create_engine, MetaData
   import MySQLdb.cursors
   engine = create_engine('mysql://root:zenoss@localhost/e2', connect_args={'cursorclass': MySQLdb.cursors.SSCursor})
   meta = MetaData(engine, reflect=True)
   conn = engine.connect()
   rs = s.execution_options(stream_results=True).execute()

详细信息可以查看 http://www.sqlalchemy.org/trac/ticket/1089


需要注意的是,使用 SSCursor 会在获取数据完成之前锁定表。这会影响使用同一连接的其他游标:来自同一连接的两个游标不能同时读取同一张表。

不过,来自不同连接的游标可以同时读取同一张表。

下面是一些代码,展示了这个问题:

import MySQLdb
import MySQLdb.cursors as cursors
import threading
import logging
import config

logger = logging.getLogger(__name__)
query = 'SELECT * FROM huge_table LIMIT 200'

def oursql_conn():
    import oursql
    conn = oursql.connect(
        host=config.HOST, user=config.USER, passwd=config.PASS,
        db=config.MYDB)
    return conn

def mysqldb_conn():
    conn = MySQLdb.connect(
        host=config.HOST, user=config.USER,
        passwd=config.PASS, db=config.MYDB,
        cursorclass=cursors.SSCursor) 
    return conn

def two_cursors_one_conn():
    """Two SSCursors can not use one connection concurrently"""
    def worker(conn):
        cursor = conn.cursor()
        cursor.execute(query)
        for row in cursor:
            logger.info(row)

    conn = mysqldb_conn()
    threads = [threading.Thread(target=worker, args=(conn, ))
               for n in range(2)]
    for t in threads:
        t.daemon = True
        t.start()
        # Second thread may hang or raise OperationalError:
        # File "/usr/lib/pymodules/python2.7/MySQLdb/cursors.py", line 289, in _fetch_row
        #   return self._result.fetch_row(size, self._fetch_type)
        # OperationalError: (2013, 'Lost connection to MySQL server during query')

    for t in threads:
        t.join()

def two_cursors_two_conn():
    """Two SSCursors from independent connections can use the same table concurrently"""    
    def worker():
        conn = mysqldb_conn()        
        cursor = conn.cursor()
        cursor.execute(query)
        for row in cursor:
            logger.info(row)

    threads = [threading.Thread(target=worker) for n in range(2)]
    for t in threads:
        t.daemon = True
        t.start()
    for t in threads:
        t.join()


logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s %(threadName)s] %(message)s',
                    datefmt='%H:%M:%S')
two_cursors_one_conn()
two_cursors_two_conn()

另外,oursql 是 Python 的另一种 MySQL 绑定库。oursql 的游标是真正的服务器端游标,默认情况下会懒加载行数据。安装了 oursql 后,如果你把

conn = mysqldb_conn()

改成

conn = oursql_conn()

那么 two_cursors_one_conn() 就可以正常运行,而不会卡住或抛出异常。

撰写回答