flaschengeist/geruecht/controller/databaseController.py

69 lines
2.0 KiB
Python

import pymysql
from geruecht import Singleton
from geruecht.model.user import User
class DatabaseController(metaclass=Singleton):
'''
DatabaesController
Connect to the Database and execute sql-executions
'''
def __init__(self, url='192.168.5.108', user='wu5', password='E1n$tein', database='geruecht'):
self.url = url
self.user = user
self.password = password
self.database = database
self.connect()
def connect(self):
try:
self.db = pymysql.connect(self.url, self.user, self.password, self.database, cursorclass=pymysql.cursors.DictCursor)
except Exception as err:
raise err
def getAllUser(self):
cursor = self.db.cursor()
def getUser(self, username):
self.connect()
retVal = None
cursor = self.db.cursor()
cursor.execute("select * from user where cn='{}'".format(username))
data = cursor.fetchone()
if data:
retVal = User(data)
self.db.close()
return retVal
def insertUser(self, data):
self.connect()
cursor = self.db.cursor()
try:
cursor.execute("insert into user (cn, dn, firstname, lastname, `group`) VALUES ('{}','{}','{}','{}','{}')".format(
data['cn'], data['dn'], data['givenName'], data['sn'], data['group']))
self.db.commit()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
self.db.close()
def updateUser(self, data):
self.connect()
cursor = self.db.cursor()
try:
cursor.execute("update user dn='{}', firstname='{}', lastname='{}', group='{}' where cn='{}'".format(
data['dn'], data['givenName'], data['sn'], data['group'], data['cn']))
self.db.commit()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
self.db.close()
if __name__ == '__main__':
db = DatabaseController(user='tim')