db.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import logging
  2. import sqlite3
  3. class connect:
  4. conn = None
  5. def __enter__(self):
  6. self.conn = sqlite3.connect('data.db')
  7. self.cursor = self.conn.cursor()
  8. return self
  9. def __exit__(self, type, value, traceback):
  10. if traceback:
  11. logging.error(traceback)
  12. self.conn.close()
  13. def execute(self, stmt, *params):
  14. self.cursor.execute(stmt, params)
  15. self.conn.commit()
  16. def select(self, stmt, *params):
  17. res = []
  18. for row in self.cursor.execute(stmt, params):
  19. if len(row) == 1:
  20. res.append(row[0])
  21. else:
  22. res.append(row)
  23. return res
  24. def init():
  25. with connect() as conn:
  26. conn.execute('''
  27. create table if not exists regions (
  28. id int not null primary key,
  29. name varchar(255) not null
  30. );
  31. ''')
  32. # conn.execute('drop table if exists localities;')
  33. conn.execute('''
  34. create table if not exists localities (
  35. id int not null primary key,
  36. name varchar(255) not null
  37. );
  38. ''')
  39. conn.execute('drop table if exists locality_relationships;')
  40. conn.execute('''
  41. create table if not exists locality_relationships (
  42. id varchar(255) not null primary key,
  43. parent int not null,
  44. child int not null
  45. )
  46. ''')
  47. init()