Last active
December 22, 2015 23:09
-
-
Save justnoise/6545156 to your computer and use it in GitHub Desktop.
Quick wrapper around MySQLdb for Python 2.4 and up
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 | |
| class SimpleDB(object): | |
| def __init__(self, h, u, p, fetchsize=10000): | |
| self.db = MySQLdb.connect(host=h, user=u, passwd=p) | |
| self.cursor = self.db.cursor() | |
| self.cursor.arraysize = fetchsize | |
| def query(self, q, params = None): | |
| '''note: if you're using more recent pythons, you can change | |
| the type checking below to check for type(params) == | |
| collections.Sequence. Unfortuantely this isn't supported in | |
| python 2.4 which is used at some sites I work at''' | |
| if params and type(params) != list and type(params) != tuple: | |
| params = [params] | |
| self.cursor.execute(q, params) | |
| result = [] | |
| num_fetched = 0 | |
| while True: | |
| r = self.cursor.fetchmany(self.cursor.arraysize) | |
| if not r: | |
| break | |
| result.extend(r) | |
| num_fetched += self.cursor.arraysize | |
| return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment