Guest User

Untitled

a guest
Jan 2nd, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. import mysql.connector
  2. from contextlib import closing
  3. import logging
  4.  
  5. log = logging.getLogger(__name__)
  6.  
  7.  
  8. class Database:
  9. """
  10. Contains code for interfacing with a MySql database
  11. """
  12.  
  13. def __init__(self, user, password, database, host):
  14. self.user = user
  15. self.password = password
  16. self.database = database
  17. self.host = host
  18. self._connection = None
  19.  
  20. @property
  21. def connection(self):
  22. if self._connection is None:
  23. log.info("Opening new database connection")
  24. self._connection = mysql.connector.connect(
  25. user=self.user,
  26. password=self.password,
  27. database=self.database,
  28. host=self.host
  29. )
  30. log.info("Connection made")
  31. if not self._connection.is_connected():
  32. self._connection.reconnect()
  33. return self._connection
  34.  
  35. def clear_connection(self):
  36. if self._connection is not None:
  37. log.info("Closing DB connection")
  38. self._connection.close()
  39. self._connection = None
  40.  
  41. def close(self):
  42. self.clear_connection()
  43.  
  44. def __enter__(self):
  45. return self
  46.  
  47. def __exit__(self, exc_type, exc_value, traceback):
  48. self.close()
  49.  
  50. def __del__(self):
  51. # Destructor - note this isn't called if circular references are involved. Prefer using with to relying on this.
  52. self.close()
  53.  
  54. def execute_sql(self, sql, sql_args=(), fetch_all=False, commit=True):
  55. return self._execute_sql(self.connection, sql, sql_args, fetch_all, commit)
  56.  
  57. @staticmethod
  58. def _execute_sql(cnx, sql, sql_args=(), fetch_all=False, commit=True, fetch_one=False):
  59. result = None
  60.  
  61. with closing(cnx.cursor()) as cursor:
  62. cursor.execute(sql, sql_args)
  63. if fetch_all:
  64. result = cursor.fetchall()
  65. elif fetch_one:
  66. result = cursor.fetchone()
  67. if commit:
  68. cnx.commit()
  69. log.debug("Executed statement: %s", cursor.statement)
  70. return result
  71.  
  72. @staticmethod
  73. def _query_result_to_dict(query_result, keys):
  74. result = {}
  75. for i, k in enumerate(keys):
  76. result[k] = tuple([x[i] for x in query_result])
  77. return result
Add Comment
Please, Sign In to add comment