import config as cfg from catquery import * import sqlite3 class DBHandler(): def __init__(self,config): self.DB = cfg.DB_NAME self.init_db() return def init_db(self): self.commit(DB_SCHEMA) # this wrapper doesn't handle exception # catch them in the caller. # another remark: we don't expect much DB throughput # and it's not necessary to maintain a long-lived connection def commit(self, str, data=None): conn = sqlite3.connect(self.DB) cur = conn.cursor() if data == None: cur.execute(str) else: cur.execute(str,data) conn.commit() conn.close() # read-only access def query(self,str): conn = sqlite3.connect(self.DB) cur = conn.cursor() res = cur.execute(str).fetchall() conn.close() return res # the insert_event exception should be handled here # because this is used as a log, and should have no effect # on the programs even if it fails def insert_event(self, _type, remarks, correspond): try: self.commit(QUERY_INSERT_EVENT, (_type,remarks,correspond)) except Exception as e: print("ERROR ","failed to insert event to the db, ignoring ",e) def count_interaction(self): try: res = self.query(QUERY_COUNT_INTERACTION) return dict(res) except: print("query failed") return None