Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- try:
- import MySQLdb
- except ImportError:
- print("Please install MySQL-python!")
- sys.exit()
- class database:
- hostname = ''
- username = ''
- password = ''
- database = ''
- db = None
- q = None
- cur = None
- def __init__(self):
- self.connect()
- def __del__(self):
- self.disconnect()
- def connect(self):
- self.db = MySQLdb.connect(host=self.hostname, user=self.username, passwd=self.password, db=self.database)
- self.cur = self.db.cursor()
- def disconnect(self):
- if self.cur != None:
- self.cur.close()
- if self.db != None:
- self.db.close()
- def query(self, query=''):
- self.cur.close()
- self.cur = self.db.cursor()
- self.q = self.cur.execute(query)
- return self.q
- def countRows(self, table='', what='*'):
- q = self.query("SELECT COUNT('+what+') FROM `"+table+"`;")
- return int(self.cur.fetchone()[0])
- def escape(self, string):
- self.cur.close()
- return MySQLdb.escape_string(string)
- def insert(self, table='', data={}):
- keys = []
- values = []
- for key,value in enumerate(data):
- del data[key]
- value = self.escape(value)
- if is_numeric(value):
- keys.append('`'+key+'`')
- values.append(str(value))
- else:
- keys.append('`'+key+'`')
- values.append('"'+str(value)+'"')
- self.query('INSERT INTO '+table+' ('+(','.join(keys))+') VALUES ('+(','.join(values))+');')
- def select(self, what='*', table='', where=None, start=None, max=None, returnAll=False):
- if where != None:
- where = 'WHERE '+where
- else:
- where = ''
- limit = ''
- if start != None and max == None:
- raise Exception('Cannot have a start value but no max value!')
- elif self.is_numeric(max):
- if start == None:
- start = '0'
- limit = 'LIMIT '+start+','+str(max)
- return self.fetch('SELECT '+what+' FROM '+table+' '+where+' '+limit+';', returnAll)
- def fetch(self, query='', returnAll=False):
- c = self.query(query)
- desc = self.cur.description
- rows = []
- for i in self.cur.description:
- rows.append(i[0])
- if(returnAll):
- Return = []
- for row in self.cur.fetchall():
- if row == None:
- break
- t = {}
- for index,value in enumerate(row):
- if self.is_numeric(value):
- t[rows[index]] = int(value)
- else:
- t[rows[index]] = str(value)
- Return.append(t)
- return Return
- else:
- row = self.cur.fetchone()
- t = {}
- for index,value in enumerate(row):
- if self.is_numeric(value):
- t[rows[index]] = int(value)
- else:
- t[rows[index]] = str(value)
- return t
- def delete(self, table, where='', limit=1):
- if where != '':
- where = 'WHERE '+where
- if not self.is_numeric(limit):
- limit = ''
- else:
- limit = 'LIMIT '+str(limit)
- return self.query('DELETE FROM '+table+' '+where+' '+limit+';')
- def is_numeric(self, var):
- try:
- float(str(var))
- return True
- except Exception:
- return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement