This commit is contained in:
Gabriel Amaral 2023-12-03 20:19:21 -03:00
parent fbecdd5af4
commit 01858f0ba6
2 changed files with 59 additions and 56 deletions

84
main.py
View File

@ -1,23 +1,28 @@
import os import os
import getpass
import mysql.connector
from table import Table from table import Table
from sql import SQL from sql import SQL
import mysql.connector
from mysql.connector import Error from mysql.connector import Error
def main(): def main():
print("Bem-vindo!") print("Bem-vindo!")
print("Deseja utilizar um banco de dados (BD) ou um arquivo .csv (CSV)?") print("Inicialmente, os dados precisam ser importados do MySQL")
print("Caso isso já tenha sido feito, os arquivos .csv serao sobreescritos")
print("Se algum update,insert ou delete tenha sido feito, ele sera perdido")
print("Eh recomendado importar as tabelas do bando de dados pelo menos no primeiro acesso")
print("Deseja importar os dados (digite BD) ou utilizar os arquivos.csv (digite CSV)?")
escolha = input() escolha = input()
tables = {}
if escolha == "CSV": if escolha == "CSV":
print("Espere os arquivos.csv carregarem...") print("Espere os arquivos.csv carregarem...")
#print("Digite a pasta onde estão os arquivos CSV:") #print("Digite a pasta onde estão os arquivos CSV:")
#csv_folder = input() #csv_folder = input()
csv_folder = "./source" csv_folder = "./source"
tables = {}
# Seleciona todos o csv presentes na pasta # Seleciona todos o csv presentes na pasta
for file in os.listdir(csv_folder): for file in os.listdir(csv_folder):
if file.endswith(".csv"): if file.endswith(".csv"):
@ -26,8 +31,8 @@ def main():
table.load_from_csv(f"{csv_folder}/{file}") table.load_from_csv(f"{csv_folder}/{file}")
tables[table_name] = table tables[table_name] = table
print("Tabelas carregadas:") print("\nTabelas carregadas:")
print(tables.keys()) print(', '.join(tables.keys())+"\n")
while True: while True:
print("Digite a query [0 para sair]:") print("Digite a query [0 para sair]:")
@ -42,13 +47,24 @@ def main():
print() print()
elif escolha == "BD": elif escolha == "BD":
try:
tables = {}
connection = mysql.connector.connect(host='localhost', print("Host (localhost):")
database='employees', host_name = input()
user='employeesdb',
password='Employees1!') print("Database (employees):")
database_name = input()
print("User:")
user_name = input()
password_name = getpass.getpass()
try:
connection = mysql.connector.connect(host=host_name,
database=database_name,
user=user_name,
password=password_name)
if connection.is_connected(): if connection.is_connected():
print("Conectado ao employees-db") print("Conectado ao employees-db")
@ -68,20 +84,6 @@ def main():
tables[table_name].save_to_csv() tables[table_name].save_to_csv()
print('Carregado', table_name) print('Carregado', table_name)
print("\n")
while True:
print("Digite a query [0 para sair]:")
query = input()
if query == "0":
break
sql = SQL(tables, query)
sql.execute()
print()
except Error as e: except Error as e:
print("Error while connecting to MySQL", e) print("Error while connecting to MySQL", e)
finally: finally:
@ -90,6 +92,36 @@ def main():
connection.close() connection.close()
print("MySQL connection is closed") print("MySQL connection is closed")
print("Espere os arquivos.csv carregarem...")
#print("Digite a pasta onde estão os arquivos CSV:")
#csv_folder = input()
csv_folder = "./source"
tables = {}
# Seleciona todos o csv presentes na pasta
for file in os.listdir(csv_folder):
if file.endswith(".csv"):
table_name = file.split(".")[0]
table = Table(table_name)
table.load_from_csv(f"{csv_folder}/{file}")
tables[table_name] = table
print("\nTabelas carregadas:")
print(', '.join(tables.keys())+"\n")
while True:
print("Digite a query [0 para sair]:")
query = input()
if query == "0":
break
sql = SQL(tables, query)
sql.execute()
print()
else: else:
print("Fora do intervalo!") print("Fora do intervalo!")

View File

@ -78,33 +78,4 @@ class Table:
f.write(data_line + '\n') f.write(data_line + '\n')
f.close() f.close()
def print_columns(self, column_list: list, where_filter: list = None, join_stmt: list = None):
if column_list[0] == '*':
column_list = self.columns
print(', '.join(column_list))
print('-' * 20)
for row in self.rows:
if where_filter is not None:
column_index = self.columns.index(where_filter[0])
row_value = row[column_index]
if where_filter[1] == '=':
if row_value != where_filter[2]:
continue
elif where_filter[1] == '>':
if row_value <= where_filter[2]:
continue
elif where_filter[1] == '<':
if row_value >= where_filter[2]:
continue
row_values = []
for column in column_list:
column_index = self.columns.index(column)
row_values.append(row[column_index])
print(', '.join(row_values))