Skip to content

Instantly share code, notes, and snippets.

@mmautner
Created March 1, 2013 02:08
Show Gist options
  • Save mmautner/5061958 to your computer and use it in GitHub Desktop.
Save mmautner/5061958 to your computer and use it in GitHub Desktop.
alternative MySQLdb cursors
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="example")
c = MySQLdb.cursors.DictCursor(db)
c.execute("SELECT * FROM students")
result = c.fetchall()
for row in result:
do_something(row['first_name'], row['last_name'], row['grade'], row['year'])
c.close()
# effectively eliminating that ugly index-referencing of the row results--
# similarly, for very large query results you can create a server-side
# cursor which prevents your cursor from downloading the entire result set
# to your local machine:
c = MySQLdb.cursors.SSCursor(db)
# The dictionary-returning version:
c = MySQLdb.cursors.SSDictCursor(db)
c.arraysize = 500
c.execute("SELECT * FROM arrivals")
result = c.fetchmany()
while result:
for row in result:
do_something(row["created_ts"], row["referrer_domain"])
result = c.fetchmany()
# obviously there's probably overhead to instantiating the dictionaries and
# you probably don't want to SELECT * in any query of this form. Then again,
# if you're worried about the former than you're probably not using python...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment