Advertisement
Guest User

Untitled

a guest
Oct 5th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import types
  3. import MySQLdb as mdb
  4.  
  5. HOST='localhost'
  6. USER='root'
  7. PASS='lol'
  8.  
  9. class MicroDb(object):
  10. _connections = {}
  11.  
  12. def __init__(self, host, user, db=None):
  13. self.host = host
  14. self.user = user
  15. self.con = None
  16. if db:
  17. self.connect(db)
  18.  
  19. def connect(self, db):
  20. con = self._connections.get((host, user, db))
  21. if con:
  22. self.connection = con
  23. else:
  24. con = mdb.connect(host=host, user=user, db=db)
  25. self._connections[(host,user,db)] = con
  26. self.connection = con
  27. return self.connection
  28.  
  29. def cursor(self, connection):
  30. if not connection:
  31. connection = self.connection
  32. return connection.cursor()
  33.  
  34. def query(self, sql, args=None, connection=None):
  35. cur = self.cursor(connection)
  36. self.cur = cur
  37. if (args):
  38. r = cur.execute(sql,args)
  39. else:
  40. r = cur.execute(sql)
  41. return cur.fetchall()
  42.  
  43. def quote(self, var):
  44. if (var == None):
  45. return "''"
  46. elif (type(var) == types.StringType):
  47. return "'%s'" % (mdb.escape_string(var),)
  48. else:
  49. return str(var)
  50. return var
  51.  
  52. def rownames(self):
  53. if not (hasattr(self.cur,'description') and self.cur.description):
  54. return []
  55. return [x[0] for x in self.cur.description]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement