mysql.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. """
  2. Mysql utilities
  3. @author: olivier.massot, 05-2020
  4. """
  5. import mysql
  6. class MySqlServer:
  7. def __init__(self, host, port, username, password, description=""):
  8. self.host = host
  9. self.port = port
  10. self.username = username
  11. self.password = password
  12. self.description = description or "no description"
  13. self.cnn = None
  14. def __repr__(self):
  15. return f"{self.username}@{self.host}:{self.port} ({self.description})"
  16. def connect(self):
  17. self.cnn = mysql.connector.connect(
  18. host=self.host,
  19. port=self.port,
  20. user=self.username,
  21. passwd=self.password
  22. )
  23. def exec(self, sql):
  24. """ Execute the sql code and return the cursor """
  25. cursor = self.cnn.cursor()
  26. logger.debug(sql)
  27. cursor.execute(sql)
  28. return cursor
  29. def db_exists(self, dbname):
  30. cursor = self.exec(f"""SELECT SCHEMA_NAME
  31. FROM INFORMATION_SCHEMA.SCHEMATA
  32. WHERE SCHEMA_NAME = '{dbname}'""")
  33. row = cursor.fetchone()
  34. return row is not None