Created
September 13, 2010 17:39
-
-
Save adamv/577700 to your computer and use it in GitHub Desktop.
Simple wrapper around MySQLdb
This file contains 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 collections | |
import MySQLdb as dbapi | |
__all__ = ['MySql'] | |
class MySql(object): | |
def __init__(self, **kwargs): | |
self.connection = dbapi.connect(**kwargs) | |
self.host_name = kwargs.get('host') | |
self.database_name = kwargs.get('db') | |
def __getattr__(self, name): | |
return getattr(self.connection, name) | |
def run(self, query, params=None): | |
""" | |
Run a query on this connection, returning all results at once. | |
""" | |
if params is None: | |
params = () | |
results = () | |
cursor = self.connection.cursor() | |
try: | |
cursor.execute(query, params) | |
names = " ".join(d[0] for d in cursor.description) | |
klass = collections.namedtuple('Results', names) | |
try: | |
results = map(klass._make, cursor.fetchall()) | |
except ProgrammingError: pass | |
finally: | |
cursor.close() | |
return results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment