AldenirLyiz

Sqlite mange

Feb 10th, 2023
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.54 KB | None | 0 0
  1. import sqlite3 as db
  2. from sqlite3 import OperationalError
  3. try:
  4.     from binApp.manageDir import Diretorio
  5.     from binApp.loging import Logger as log
  6. except ModuleNotFoundError:
  7.     from manageDir import Diretorio
  8.  
  9.  
  10. class HandlerDB:
  11.     __ROOT_DIR__ = Diretorio()
  12.     __DATABASE__ = 'dadosCobranca.db'
  13.  
  14.     def __init__(self) -> None:
  15.         try:
  16.             self.banco = db.connect(f'{self.__ROOT_DIR__}/dataBase/{self.__DATABASE__}')
  17.             self.cursor = self.banco.cursor()
  18.         except OperationalError as _erro:
  19.             message = f"""Problema ao Conectar com o Banco de dados.\n
  20.                ->Possivel erro de permissao de leitura/gravacao,
  21.                Contate o administrador do Sistema.
  22.                ERRO:{_erro}"""
  23.             log.retListApp(message)
  24.             self.ErrConnectDB(message)
  25.  
  26.  
  27.     def queryAdd(self, _data:dict):
  28.         _table_ = f"{_data['nome da rota:']}{_data['data da rota:']}"
  29.         temp_table_create = f"CREATE TABLE {_table_} {tuple(_data.keys())};"
  30.         temp_data_adict = f"INSERT INTO {_table_} VALUES{tuple(_data.values())};"
  31.  
  32.         if self.verifyTable(_table=_table_):
  33.             self.cursor.execute(temp_table_create)
  34.             self.banco.commit()
  35.             self.cursor.execute(temp_data_adict)
  36.             self.banco.commit()
  37.             return "All data are aded"
  38.         else:
  39.             return f"A tabela {_table_} ja existe no banco de dados!"
  40.  
  41.  
  42.     def queryRequestTables(self, _table:str=None, _last:bool=False) -> list:
  43.        
  44.         temp_request_table = "SELECT name FROM sqlite_master WHERE type='table';"
  45.         temp_request_data = f"SELECT * FROM '{_table}'"
  46.  
  47.         if _last:
  48.             try:
  49.                 temp = self.cursor.execute(temp_request_table).fetchall()
  50.                 return temp
  51.             except db.Error as _erro:
  52.                 raise _erro
  53.  
  54.         if not self.verifyTable(_table):
  55.             return "Tabela Inexistente"
  56.         else:
  57.             try:
  58.                 temp = self.cursor.execute(temp_request_data)
  59.                 return temp.fetchall()
  60.             except db.Error as _erro:
  61.                 raise _erro
  62.    
  63.  
  64.     def queryRequestColumns(self, _table:str) -> list:
  65.         temp_query_columns = f"PRAGMA table_info({_table})"
  66.        
  67.         if self.verifyTable(_table):
  68.             temp_data = self.cursor.execute(temp_query_columns).fetchall()
  69.             return [column[1] for column in temp_data]
  70.         else:
  71.             return "Tabela Inexistente"
  72.  
  73.  
  74.     def verifyTable(self, _table:str=None, _verify_all=False) -> bool:
  75.         if _verify_all:
  76.             temp = self.cursor.execute(
  77.                 f"SELECT name FROM sqlite_master WHERE type='table';").fetchone()
  78.             if temp != None:
  79.                 return True
  80.             else: return False
  81.        
  82.         temp_check_table = self.cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{_table}';").fetchone()
  83.         if temp_check_table != []:
  84.             return True
  85.         else:
  86.             return False
  87.  
  88.  
  89.     class ErrConnectDB(Exception):
  90.         pass
  91.  
  92.  
  93. if __name__ == "__main__":
  94.     from teste import dictDados
  95.     hand = HandlerDB()
  96.     #print(hand.verifyTable('Campina'))
  97.     #print(Diretorio.retWayFile('dataBase', 'dadosCobranca.db'))
  98.     print(hand.queryAdd("campina19_02_2023", dictDados))
  99.     #temp = hand.queryRequestTables(_table='Campina21_07_2022', _last=False)
  100.     #print(temp)
  101.     #table = hand.queryRequestTables(_last=True)
  102.     #print(hand.queryRequestTables(_table=table[0][0]))
  103.  
  104.  
Add Comment
Please, Sign In to add comment