Add Docstring/Implement error handling/Safer query

This commit is contained in:
Sirin Puenggun 2023-05-07 23:47:03 +07:00
parent 90f68ba2bb
commit 66b503bfd0

View File

@ -1,21 +1,50 @@
import sqlite3 import sqlite3
import os.path import os.path
# Static path
current_dir = os.path.dirname(os.path.abspath(__file__)) current_dir = os.path.dirname(os.path.abspath(__file__))
db_path = (current_dir + r"\data\food_data.db") db_path = (current_dir + r"\data\food_data.db")
class FoodSearch: 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): def __init__(self):
self.status = os.path.exists(db_path) if not os.path.exists(db_path):
if self.status: raise FileNotFoundError("Database file not found.")
self.conn = sqlite3.connect(db_path)
else: self.db_path = db_path
raise FileNotFoundError
self.cursor = self.conn.cursor()
def search(self, user_input) -> list: def search(self, user_input) -> list:
query = f"SELECT * FROM food_data WHERE product_name LIKE '%{user_input}%'" """
self.cursor.execute(query) Search for food data based on the user's input.
results = self.cursor.fetchall()
Parameters:
return results 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 []