External Exam Download Resources Web Applications Games Recycle Bin

Interacting with the Restaurant Results

interacting1.py

import sqlite3

try:
  db = sqlite3.connect('restaurant.db')
  db.row_factory = sqlite3.Row
  cursor = db.cursor()
  cursor.execute("SELECT * FROM menu")
  result = cursor.fetchall()

  items = ""
  if len(result) > 0:
    for row in result:
      items += str(row['num']) + " --> " + row['title'] + "\n"
  print(items)

  choice = int(input("Enter num of food to see price: "))
  for row in result:
    if row['num'] == choice:
      print("$" + str(row['price']))
  
except Exception as error_msg:
  print("An error occured:", error_msg)
finally:
  db.close()

interacting2.py

import sqlite3

prompt = """
entree 
burger
salad
pasta
dessert
-------
Enter category: """

querystring = '''
SELECT title, price
FROM menu
WHERE category == ?
'''

category = input(prompt)

try:
  db = sqlite3.connect('restaurant.db')
  cursor = db.cursor()
  cursor.execute(querystring, (category,)) #(querystring, (tuple list of parameters))
  result = cursor.fetchall()
  print(result)
except Exception as error_msg:
  print("An error occured:", error_msg)
finally:
  db.close()

interacting3.py

import sqlite3

prompt = """
entree 
burger
salad
pasta
dessert
-------
Enter category: """

querystring = '''
SELECT title, price
FROM menu
WHERE category == ?
  AND price <= ?
'''

category = input(prompt)
price_limit_high = float(input('Enter upper price limit (decimal): '))

try:
  db = sqlite3.connect('restaurant.db')
  cursor = db.cursor()
  cursor.execute(querystring, (category, price_limit_high, )) #parameters go into ?, left to right
  result = cursor.fetchall()
  print(result)
except Exception as error_msg:
  print("An error occured:", error_msg)
finally:
  db.close()