database.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import mysql.connector
  2. import config as conf
  3. class Database:
  4. def __init__(self):
  5. self.connection = mysql.connector.connect(host=conf.DB_HOST,
  6. user=conf.DB_USER,
  7. password=conf.DB_PASS,
  8. database=conf.DB_NAME)
  9. self.cursor = self.connection.cursor(dictionary=True)
  10. def cursor(self):
  11. return self.cursor
  12. def commit(self):
  13. self.connection.commit()
  14. def close(self, commit=True):
  15. if commit:
  16. self.commit()
  17. self.connection.close()
  18. def fetchone(self):
  19. return self.cursor.fetchone()
  20. def fetchall(self):
  21. return self.cursor.fetchall()
  22. def execute(self, sql, params=None):
  23. return self.cursor.execute(sql, params or ())
  24. def sql_simple_check(self, sql: str):
  25. self.execute(sql)
  26. response = self.fetchone()
  27. if response is None:
  28. return False
  29. else:
  30. for v in response.values():
  31. return v
  32. def sql_parse_users(self, sql: str):
  33. self.execute(sql)
  34. result_set = self.fetchall()
  35. users_list = []
  36. if len(result_set) == 0:
  37. return False
  38. elif len(result_set) > 0:
  39. for row in result_set:
  40. users_data = {"ID": row['id'],
  41. "ФИО": row['name'],
  42. "Номер телефона": row['phone']}
  43. users_list.append(users_data)
  44. return users_list
  45. def sql_query_send(self, sql):
  46. self.execute(sql)
  47. self.commit()
  48. self.close()
  49. # Db = Database()
  50. # data = Db.sql_simple_check("select tg_id from user_table where tg_id = 338836490 and approved = 0")
  51. # print(data)