Skip to main content.
June 26th, 2008

Python - How to Make MySQLdb Store Query Results on the Server

Sometimes I’ll want to run a query against a MySQL database from Python that returns a large result set. So large in fact that Python hits a memory error.

One way around this is to have the Python MySQL library (MySQLdb) store the results from a query on the database server and bring them back to you one at a time as you request them.

Here’s how you set that up:

import MySQLdb
import MySQLdb.cursors #Make sure to import this seperately

#build your connection object normally but pass it a cursorclass keyword
db=MySQLdb.connect(host=HOSTNAME,user=USERNAME,passwd=PASSWORD,db=DATABASE,
            cursorclass=MySQLdb.cursors.SSCursor)

#Usage

cursor=db.cursor()
cursor.execute('select huge_column from huge_table')
#iterate over the results pulling them down from the server on each iteration
for row in cursor:
    print row
cursor.close()

Posted by Greg Pinero (Primary Searcher) in Python

This entry was posted on Thursday, June 26th, 2008 at 8:49 pm and is filed under Python. You can follow any responses to this entry through the comments RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Python - How to Make MySQLdb Store Query Results on the Server”

  1. mike bayer says:

    according to my sources, this mode has the unfortunate side effect of locking the entire table for the duration of the fetch - this is because it isn’t using a true server side cursor. So not extremely useful for a concurrent environment :/

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>