Advertisement
Debug__

[Python] Database Class

Nov 20th, 2014
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.85 KB | None | 0 0
  1. import sys
  2. try:
  3.     import MySQLdb
  4. except ImportError:
  5.     print("Please install MySQL-python!")
  6.     sys.exit()
  7.  
  8. class database:
  9.     hostname = ''
  10.     username = ''
  11.     password = ''
  12.     database = ''
  13.     db = None
  14.     q = None
  15.     cur = None
  16.     def __init__(self):
  17.         self.connect()
  18.  
  19.     def __del__(self):
  20.         self.disconnect()
  21.  
  22.     def connect(self):
  23.         self.db = MySQLdb.connect(host=self.hostname, user=self.username, passwd=self.password, db=self.database)
  24.         self.cur = self.db.cursor()
  25.  
  26.  
  27.     def disconnect(self):
  28.         if self.cur != None:
  29.             self.cur.close()
  30.         if self.db != None:
  31.             self.db.close()
  32.  
  33.     def query(self, query=''):
  34.         self.cur.close()
  35.         self.cur = self.db.cursor()
  36.         self.q = self.cur.execute(query)
  37.         return self.q
  38.  
  39.     def countRows(self, table='', what='*'):
  40.         q = self.query("SELECT COUNT('+what+') FROM `"+table+"`;")
  41.         return int(self.cur.fetchone()[0])
  42.  
  43.     def escape(self, string):
  44.         self.cur.close()
  45.         return MySQLdb.escape_string(string)
  46.  
  47.     def insert(self, table='', data={}):
  48.         keys = []
  49.         values = []
  50.         for key,value in enumerate(data):
  51.             del data[key]
  52.             value = self.escape(value)
  53.             if is_numeric(value):
  54.                 keys.append('`'+key+'`')
  55.                 values.append(str(value))
  56.             else:
  57.                 keys.append('`'+key+'`')
  58.                 values.append('"'+str(value)+'"')
  59.         self.query('INSERT INTO '+table+' ('+(','.join(keys))+') VALUES ('+(','.join(values))+');')
  60.  
  61.     def select(self, what='*', table='', where=None, start=None, max=None, returnAll=False):
  62.         if where != None:
  63.             where = 'WHERE '+where
  64.         else:
  65.             where = ''
  66.  
  67.         limit = ''
  68.         if start != None and max == None:
  69.             raise Exception('Cannot have a start value but no max value!')
  70.         elif self.is_numeric(max):
  71.             if start == None:
  72.                 start = '0'
  73.             limit = 'LIMIT '+start+','+str(max)
  74.         return self.fetch('SELECT '+what+' FROM '+table+' '+where+' '+limit+';', returnAll)
  75.  
  76.     def fetch(self, query='', returnAll=False):
  77.         c = self.query(query)
  78.         desc = self.cur.description
  79.         rows = []
  80.         for i in self.cur.description:
  81.             rows.append(i[0])
  82.         if(returnAll):
  83.             Return = []
  84.             for row in self.cur.fetchall():
  85.                 if row == None:
  86.                     break
  87.                 t = {}
  88.                 for index,value in enumerate(row):
  89.                     if self.is_numeric(value):
  90.                         t[rows[index]] = int(value)
  91.                     else:
  92.                         t[rows[index]] = str(value)
  93.                 Return.append(t)
  94.             return Return
  95.         else:
  96.             row = self.cur.fetchone()
  97.             t = {}
  98.             for index,value in enumerate(row):
  99.                 if self.is_numeric(value):
  100.                     t[rows[index]] = int(value)
  101.                 else:
  102.                     t[rows[index]] = str(value)
  103.             return t
  104.  
  105.     def delete(self, table, where='', limit=1):
  106.         if where != '':
  107.             where = 'WHERE '+where
  108.         if not self.is_numeric(limit):
  109.             limit = ''
  110.         else:
  111.             limit = 'LIMIT '+str(limit)
  112.         return self.query('DELETE FROM '+table+' '+where+' '+limit+';')
  113.  
  114.     def is_numeric(self, var):
  115.         try:
  116.             float(str(var))
  117.             return True
  118.         except Exception:
  119.             return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement