Try it!
Description
import csv
while True:
print("SQL CSV tool\nEnter help for more information\nEnter exit
to quit\n")
print("Enter the SQL query to execute:")
command = input("> ")
if command.lower() == "exit":
break
elif command.lower() == "help":
print("This tool allows you to execute SQL queries and
export the results to a CSV file.\nTo use the tool, simply enter your
SQL query and press Enter.\nThe default path for the csv file is a
dummy CSV file.\nThe results will be saved to a file named
'output.csv' in the current directory.")
elif command.strip() == "":
print("Please enter a valid SQL query.")
continue
else:
phrases = command.strip().split()
phrases = [phrase.lower().strip(',') for phrase in
phrases]
if len(phrases) < 4 or phrases[0] != "select":
print("Only SELECT queries are allowed. Please enter
a valid SQL query.")
continue
else:
select_index = phrases.index("select")
from_index = phrases.index("from")
where_index = phrases.index("where") if "where" in
phrases else None
total_selected = from_index - select_index - 1
selected_columns = phrases[select_index +
1:from_index]
total_from = phrases[from_index + 1:where_index] if
where_index is not None else phrases[from_index + 1:]
if total_selected == 0:
print("Please specify at least one column to
select.")
continue
if total_from == 0:
total_from =
["../assets/test-data/departments.csv"]
if where_index is not None:
total_where = len(phrases) - where_index -
1
if total_where == 0:
print("Please specify a condition for
the WHERE clause.")
continue
else:
where_condition = phrases[where_index +
1:]
with open(total_from[0], mode='r') as file:
reader = csv.DictReader(file)
results = []
for row in reader:
if where_index is not None:
condition = "
".join(where_condition)
if eval(condition, {}, row):
results.append({col:
row[col] for col in selected_columns})
else:
results.append({col: row[col] for col in
selected_columns})
print(results)
The test data is here if you want to view it.
Previous Day
Next Day