Primo punto: un cursore db-api di Python è un iteratore. A meno che tu non abbia davvero bisogno di un intero blocco in memoria, sfruttalo. Invece di:
cursor.execute("SELECT * FROM mytable") rows = cursor.fetchall() for row in rows: do_something_with(row) scrivi semplicemente:
cursor.execute("SELECT * FROM mytable") for row in cursor: do_something_with(row) Se il tuo driver continua a non fare streaming a dovere, è il momento di aggiungere LIMIT e OFFSET:
# py2 / py3 compat try: # xrange is defined in py2 only xrange except NameError: # in py3 range is the lazy one xrange = range cursor.execute("SELECT count(*) FROM mytable") count = cursor.fetchone()[0] batch_size = 42 # whatever suits you for offset in xrange(0, count, batch_size): cursor.execute( "SELECT * FROM mytable LIMIT %s OFFSET %s", (batch_size, offset)) for row in cursor: do_something_with(row) Un avvertimento sull'approccio con l'offset: OFFSET costringe il server a scansionare e scartare righe, quindi degrada sulle tabelle grandi. La paginazione keyset — WHERE id > last_seen_id ORDER BY id LIMIT 42 — resta veloce a qualsiasi profondità. Nota inoltre che con il cursore predefinito di MySQLdb/MySQL Connector il client bufferizza l'intero result set: usa le varianti non bufferizzate SSCursor o MySQLCursorDictCursor se ti serve davvero uno streaming lato server.