tle_database.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import mariadb
  2. import logging
  3. import sys
  4. logger = logging.getLogger('tle_fetcher.' + __name__)
  5. class TleDatabase:
  6. def __init__(self):
  7. self.conn = None
  8. def connect_db(self):
  9. # Connect to MariaDB
  10. try:
  11. conn = mariadb.connect(
  12. user='tle_getter',
  13. host='localhost',
  14. port=3306,
  15. database='celestrak_tles'
  16. )
  17. except mariadb.Error as e:
  18. logger.error("Error connecting to MariaDB Platform: %s", e.msg)
  19. sys.exit(1)
  20. self.conn = conn
  21. def delete_rows(self):
  22. cur = self.conn.cursor()
  23. try:
  24. cur.execute('delete from sat_groups')
  25. cur.execute('delete from tles')
  26. except mariadb.Error as e:
  27. logger.error("Error clearing tables: %s", e.msg)
  28. self.conn.commit()
  29. def update_tles(self, tles: dict):
  30. cur = self.conn.cursor()
  31. try:
  32. cur.executemany('INSERT INTO tles (sat, tle) values (?,?)', list(tles.items()))
  33. except mariadb.Error as e:
  34. logger.error("Error updating TLEs: %s", e.msg)
  35. self.conn.commit()
  36. def update_sat_group(self, group: list):
  37. cur = self.conn.cursor()
  38. try:
  39. cur.executemany('INSERT INTO sat_groups (sat, group_name) values (?,?)', group)
  40. except mariadb.Error as e:
  41. logger.error("Error updating groups: %s", e.msg)
  42. self.conn.commit()
  43. def close_db(self):
  44. self.conn.close()