External Exam Download Resources Web Applications Games Recycle Bin

Adding new foods to the Restaurant DB

inserting1.py

import sqlite3

insertionSQLstring = """
INSERT INTO menu (num, title, category, description, price, calories)
  VALUES (?, ?, ?, ?, ?, ?)
"""

try:
  db = sqlite3.connect('restaurant.db')
  cursor = db.cursor()
  cursor.execute("SELECT num + 1 FROM menu ORDER BY num DESC LIMIT 1") #next available number

  #set up parameters for INSERT:
  num = cursor.fetchone()[0]
  title = input("Title: ")
  category = input("Category: ")
  description = input("Discription: ")
  price = float(input("Price ($): "))
  calories = int(input("Calories: "))

  #execute INSERT query, and write changes to disk:
  cursor.execute(insertionSQLstring,(num, title, category, description, price, calories))
  db.commit()
  print("Database changes made. Open in DB Browser for SQLite to see changes.") 
  
except Exception as error_msg:
  #rollback important for database integrity, incase erroneous data was saved:
  db.rollback()
  print("An error occured:", error_msg)
  
finally:
  db.close()

inserting2.py

import sqlite3

insertionSQLstring = """
INSERT INTO menu (num, title, category, description, price, calories)
  VALUES (?, ?, ?, ?, ?, ?)
"""

dumpling_desc = "Steamed pork dumplings with Szechwan dipping sauce."
soup_desc = "Caramelized onions simmered in au jus topped with a crouton and melted Swiss."
cheeseburger_desc = "White cheddar, lettuce, tomatoes, red onions and pickles."

lots_of_new_foods = [
  (21, "Steamed Dumplings", "entree", dumpling_desc, 11.95, 590),
  (22, "French Onion Soup", "entree", soup_desc, 9.95, 590),
  (23, "Cheeseburger", "burger", cheeseburger_desc, 10.00, 820)
]

try:
  db = sqlite3.connect('restaurant.db')
  cursor = db.cursor()
  
  #bulk execute INSERT query:
  cursor.executemany(insertionSQLstring, lots_of_new_foods)
  db.commit()
  print("Database changes made. Open in DB Browser for SQLite to see changes.") 
  
except Exception as error_msg:
  db.rollback()
  print("An error occured:", error_msg)
  
finally:
  db.close()

inserting3.py

import sqlite3

insertionSQLstring = """
INSERT OR REPLACE INTO menu (num, title, category, description, price, calories)
  VALUES (3, "Buffalo Burger", "burger", "Out of stock", -1.00, 920)
"""

try:
  db = sqlite3.connect('restaurant.db')
  cursor = db.cursor()
  cursor.execute(insertionSQLstring)
  db.commit()
  print("Database changes made. Open in DB Browser for SQLite to see changes.") 
  
except Exception as error_msg:
  db.rollback()
  print("An error occured:", error_msg)
  
finally:
  db.close()