Created
October 5, 2016 18:20
-
-
Save ggerrietts/35338dab559e13fc6ca3f1b3169d68de to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
import types | |
import MySQLdb as mdb | |
HOST='localhost' | |
USER='root' | |
PASS='lol' | |
class MicroDb(object): | |
_connections = {} | |
def __init__(self, host, user, db=None): | |
self.host = host | |
self.user = user | |
self.con = None | |
if db: | |
self.connect(db) | |
def connect(self, db): | |
con = self._connections.get((host, user, db)) | |
if con: | |
self.connection = con | |
else: | |
con = mdb.connect(host=host, user=user, db=db) | |
self._connections[(host,user,db)] = con | |
self.connection = con | |
return self.connection | |
def cursor(self, connection): | |
if not connection: | |
connection = self.connection | |
return connection.cursor() | |
def query(self, sql, args=None, connection=None): | |
cur = self.cursor(connection) | |
self.cur = cur | |
if (args): | |
r = cur.execute(sql,args) | |
else: | |
r = cur.execute(sql) | |
return cur.fetchall() | |
def quote(self, var): | |
if (var == None): | |
return "''" | |
elif (type(var) == types.StringType): | |
return "'%s'" % (mdb.escape_string(var),) | |
else: | |
return str(var) | |
return var | |
def rownames(self): | |
if not (hasattr(self.cur,'description') and self.cur.description): | |
return [] | |
return [x[0] for x in self.cur.description] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment