Advertisement
Guest User

Untitled

a guest
Mar 16th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. class UseDatabase:
  2. def __init__(self, configuration):
  3. """ Initialisation code which executes the context manager
  4. is CREATED. """
  5. self.host = configuration['DB_HOST']
  6. self.user = configuration['DB_USER']
  7. self.passwd = configuration['DB_PASSWD']
  8. self.db = configuration['DB']
  9.  
  10. def __enter__(self):
  11. """ Set-up code which executes BEFORE the body of the
  12. with statement. """
  13. self.conn = mysql.connector.connect(host=self.host,
  14. user=self.user,
  15. password=self.passwd,
  16. database=self.db,)
  17. self.cursor = self.conn.cursor()
  18. return(self.cursor)
  19.  
  20. def __exit__(self, exc_type, exv_value, exc_traceback):
  21. """ Tear-down code with executes AFTER the body of the
  22. with statement.
  23. The three extra parameters to __exit__() contain information
  24. related to any exception which may have occurred while running
  25. the body of the with statement. """
  26. self.cursor.close()
  27. self.conn.commit()
  28. self.conn.close()
  29.  
  30. config = {'DB_HOST' : 'localhost','DB_USER' : 'root' , 'DB_PASSWD' : '******', 'DB' : 'db'}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement