database.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import mysql.connector
  2. from bot import config as conf
  3. class Database:
  4. def __init__(self):
  5. try:
  6. self.connection = mysql.connector.connect(host=conf.DB_HOST,
  7. user=conf.DB_USER,
  8. password=conf.DB_PASS,
  9. database=conf.DB_NAME)
  10. self.cursor = self.connection.cursor(dictionary=True)
  11. except mysql.connector.Error as err:
  12. print("Something went wrong: {}".format(err))
  13. def cursor(self):
  14. return self.cursor
  15. def commit(self):
  16. self.connection.commit()
  17. def close(self, commit=True):
  18. if commit:
  19. self.commit()
  20. self.connection.close()
  21. def fetchone(self):
  22. return self.cursor.fetchone()
  23. def fetchall(self):
  24. return self.cursor.fetchall()
  25. def execute(self, sql, params=None):
  26. return self.cursor.execute(sql, params or ())
  27. def sql_fetchone(self, sql: str):
  28. self.execute(sql)
  29. response = self.fetchone()
  30. if response is None:
  31. return 'None'
  32. else:
  33. for v in response.values():
  34. return v
  35. def sql_fetchall(self, sql: str):
  36. self.execute(sql)
  37. response = self.fetchall()
  38. return response
  39. def sql_query_send(self, sql: str):
  40. self.execute(sql)
  41. self.commit()