Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pymysql
- class Database:
- def __init__(self):
- host = '127.0.0.1'
- user = 'root'
- password = ''
- db = 'API'
- self.con = pymysql.connect(host=host, user=user, password=password, db=db, cursorclass=pymysql.cursors.DictCursor, autocommit=True)
- self.cur = self.con.cursor()
- def getUser(self, id):
- sql = 'SELECT * from users where id = %d'
- self.cur.execute(sql, (id))
- result = self.cur.fetchall()
- return result
- def getAllUsers(self):
- sql = 'SELECT * from users'
- self.cur.execute(sql)
- result = self.cur.fetchall()
- return result
- def AddUser(self, firstName, lastName, email):
- sql = "INSERT INTO `users` (`firstName`, `lastName`, `email`) VALUES (%s, %s, %s)"
- self.cur.execute(sql, (firstName, lastName, email))
- import pymysql
- class MyDatabase():
- def __init__(self):
- self.host = '127.0.0.1'
- self.user = 'root'
- self.password = ''
- self.db = 'API'
- self.con = None
- self.cur = None
- def __enter__(self):
- # connect to database
- self.con = pymysql.connect(host=self.host, user=self.user, password=self.password, db=self.db, cursorclass=pymysql.cursors.DictCursor, autocommit=True)
- self.cur = self.con.cursor()
- return self.cur
- def __exit__(self, exc_type, exc_val, traceback):
- # params after self are for dealing with exceptions
- self.con.close()
- # import your custom context manager created from the step above
- # if you called your custom context manager file my_database.py: from my_database import MyDatabase
- import <custom_context_manager>
- class User:
- def getUser(self, id):
- sql = 'SELECT * from users where id = %d'
- with MyDatabase() as db:
- db.execute(sql, (id))
- result = db.fetchall()
- return result
- def getAllUsers(self):
- sql = 'SELECT * from users'
- with MyDatabase() as db:
- db.execute(sql)
- result = db.fetchall()
- return result
- def AddUser(self, firstName, lastName, email):
- sql = "INSERT INTO `users` (`firstName`, `lastName`, `email`) VALUES (%s, %s, %s)"
- with MyDatabase() as db:
- db.execute(sql, (firstName, lastName, email))
- from contextlib import contextmanager
- import pymysql
- @contextmanager
- def my_database():
- try:
- host = '127.0.0.1'
- user = 'root'
- password = ''
- db = 'API'
- con = pymysql.connect(host=host, user=user, password=password, db=db, cursorclass=pymysql.cursors.DictCursor, autocommit=True)
- cur = con.cursor()
- yield cur
- finally:
- con.close()
- with my_database() as db:
- sql = <whatever sql stmt you wish to execute>
- #db action
- db.execute(sql)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement