From 66b503bfd04b5a88d983ab67f89b3b9effafc671 Mon Sep 17 00:00:00 2001 From: Sirin Puenggun Date: Sun, 7 May 2023 23:47:03 +0700 Subject: [PATCH] Add Docstring/Implement error handling/Safer query --- Essential/FoodSearch.py | 51 ++++++++++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/Essential/FoodSearch.py b/Essential/FoodSearch.py index a9f817d..635855c 100644 --- a/Essential/FoodSearch.py +++ b/Essential/FoodSearch.py @@ -1,21 +1,50 @@ import sqlite3 import os.path +# Static path current_dir = os.path.dirname(os.path.abspath(__file__)) db_path = (current_dir + r"\data\food_data.db") class FoodSearch: + """ + A class for searching food data in a SQLite database. + + Methods: + search(user_input): Search for food data based on user input. + + Usage: + food_search = FoodSearch() + results = food_search.search("apple") + """ + def __init__(self): - self.status = os.path.exists(db_path) - if self.status: - self.conn = sqlite3.connect(db_path) - else: - raise FileNotFoundError - self.cursor = self.conn.cursor() + if not os.path.exists(db_path): + raise FileNotFoundError("Database file not found.") + + self.db_path = db_path def search(self, user_input) -> list: - query = f"SELECT * FROM food_data WHERE product_name LIKE '%{user_input}%'" - self.cursor.execute(query) - results = self.cursor.fetchall() - - return results \ No newline at end of file + """ + Search for food data based on the user's input. + + Parameters: + user_input (str): The input provided by the user to search for food data. + + Returns: + list: A list of tuples representing the search results from the database. + + Raises: + sqlite3.Error: If there is an error in executing the database query. + """ + + try: + with sqlite3.connect(self.db_path) as conn: + cursor = conn.cursor() + query = "SELECT * FROM food_data WHERE product_name LIKE ?" + cursor.execute(query, (f"%{user_input}%",)) + results = cursor.fetchall() + return results + except sqlite3.Error as e: + + print(f"Database error: {e}") + return [] \ No newline at end of file