Skip to content

Commit

Permalink
added sql tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
TK committed Nov 29, 2020
1 parent f44a201 commit 704d6ae
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
37 changes: 37 additions & 0 deletions database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import sqlite3

CREATE_BEANS_TABLE = "CREATE TABLE IF NOT EXISTS beans (id INTEGER PRIMARY KEY, name TEXT, method TEXT, rating INTEGER);"
INSERT_BEAN = "INSERT INTO beans (name, method, rating) VALUES(?, ?, ?);"

GET_ALL_BEANS = "SELECT * FROM beans;"

GET_BEANS_BY_NAME = "SELECT * FROM beans WHERE name = ?;"

GET_BEST_PREPARATION_FOR_BEAN ="""
SELECT * FROM beans
WHERE name = ?
ORDER BY rating DESC
LIMIT 1;"""

def connect():
return sqlite3.connect("data.db")

def create_tables(connection):
with connection:
connection.execute(CREATE_BEANS_TABLE)

def add_bean(connection, name, method, rating):
with connection:
connection.execute(INSERT_BEAN, (name, method, rating))

def get_all_beans(connection):
with connection:
return connection.execute(GET_ALL_BEANS).fetchall()

def get_beans_by_name(connection, name):
with connection:
return connection.execute(GET_BEANS_BY_NAME, (name,)).fetchall()

def get_best_preparation_for_bean(connection, name):
with connection:
return connection.execute(GET_BEST_PREPARATION_FOR_BEAN, (name,)).fetchone()
55 changes: 55 additions & 0 deletions sql_beans_tutorial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import database

MENU_PROMPT = """
Choose option:
1. Add a new bean
2. See all beans
3. Find a bean by name
4. See best preparation
5. Exit
"""

def menu():
connection = database.connect()
database.create_tables(connection)

while (user_input := input(MENU_PROMPT)) != "5":
if user_input == "1":
prompt_add_new_bean(connection)
elif user_input == "2":
prompt_see_all_beans(connection)
elif user_input == "3":
prompt_find_bean(connection)
elif user_input == "4":
prompt_find_best_method(connection)
else:
print("Invalid input")

def prompt_add_new_bean(connection):
name = input("Enter bean name: ")
method = input("Enter preparation method: ")
rating = int(input("Enter rating: "))

database.add_bean(connection, name, method, rating)

def prompt_see_all_beans(connection):
beans = database.get_all_beans(connection)
for bean in beans:
print(f"{bean[1]} {bean[2]} - {bean[3]}/ 100 ")

def prompt_find_bean(connection):
name = input("Enter bean name to find: ")
beans = database.get_beans_by_name(connection, name)

for bean in beans:
print(f"{bean[1]} {bean[2]} - {bean[3]}/ 100")

def prompt_find_best_method(connection):
name = input("Enter bean name to find: ")
best_method = database.get_best_preparation_for_bean(connection, name)

print(f"The best bean preparation for {name} is: {best_method[2]}.")


menu()

0 comments on commit 704d6ae

Please sign in to comment.