import logging import sqlite3 class connect: conn = None def __enter__(self): self.conn = sqlite3.connect('data.db') self.cursor = self.conn.cursor() return self def __exit__(self, type, value, traceback): if traceback: logging.error(traceback) self.conn.close() def execute(self, stmt, *params): self.cursor.execute(stmt, params) self.conn.commit() def select(self, stmt, *params): res = [] for row in self.cursor.execute(stmt, params): if len(row) == 1: res.append(row[0]) else: res.append(row) return res def init(): with connect() as conn: conn.execute(''' create table if not exists regions ( id int not null primary key, name varchar(255) not null ); ''') # conn.execute('drop table if exists localities;') conn.execute(''' create table if not exists localities ( id int not null primary key, name varchar(255) not null ); ''') conn.execute('drop table if exists locality_relationships;') conn.execute(''' create table if not exists locality_relationships ( id varchar(255) not null primary key, parent int not null, child int not null ) ''') init()