Guest User

Untitled

a guest
Oct 24th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. class UseMySQL:
  2. # Importing MySQLdb and as a smaller name for reusing it.
  3. # To install MySQL Python connection use below command:
  4. # pip install mysqlclient
  5. import MySQLdb as _mysql
  6.  
  7. def __init__(self, host, user, password, db):
  8. """
  9. Initializing MySQL details in init method.
  10.  
  11. Args:
  12. self
  13. host: Host name of the machine.
  14. user: Username of mySQL DB.
  15. password: Password of mySQL DB.
  16. db: Database name of mySQL DB.
  17. """
  18. self._host = host
  19. self._user = user
  20. self._password = password
  21. self._db = db
  22.  
  23. def __enter__(self):
  24. """
  25. This data model/dunder method is used
  26. to employ auto open of my sql connection
  27. and cursor inside 'with' and in turn
  28. close them inside the same with the help
  29. of exit method in order to avoid not so
  30. closed database connections.
  31.  
  32. Args:
  33. self
  34.  
  35. Returns:
  36. self.cursor
  37. """
  38. self._conn = self._mysql.connect(
  39. host=self._host, user=self._user, passwd=self._password, db=self._db)
  40. self.cursor = self._conn.cursor()
  41. return self.cursor
  42.  
  43. def __exit__(self, exception_type, exception_value, traceback):
  44. """
  45. This data model/dunder method is used to employ
  46. auto close of connection and cursor as with block ends.
  47.  
  48. Args:
  49. self
  50. exception_type: Type of Exception.
  51. exception_value: Exception Value.
  52. traceback: Traceback value.
  53. """
  54. self.cursor.close()
  55. self._conn.close()
  56.  
  57.  
  58. with UseMySQL(host="localhost", user="someuser", password="somepassword", db="sakila") as mySqlObj:
  59. cursor = mySqlObj
  60. cursor.execute("SELECT * FROM ACTOR")
  61. for tup1 in cursor.fetchall():
  62. print(tup1)
Add Comment
Please, Sign In to add comment