Skip to content

Instantly share code, notes, and snippets.

@adamv
Created September 13, 2010 17:39
Show Gist options
  • Save adamv/577700 to your computer and use it in GitHub Desktop.
Save adamv/577700 to your computer and use it in GitHub Desktop.
Simple wrapper around MySQLdb
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