Created
March 1, 2013 02:08
-
-
Save mmautner/5061958 to your computer and use it in GitHub Desktop.
alternative MySQLdb cursors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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