IWS_WS24_clean_architecture/db/db_product.py

101 lines
2.8 KiB
Python

import sqlite3
class ProductDatabase:
def __init__(self, db_file):
"""Initialize the ProductDatabase with a connection to the SQLite database."""
self.conn = sqlite3.connect(db_file)
def add_product(self, product):
"""Add a new product to the products table."""
sql = "INSERT INTO products (name, price, quantity) VALUES (?, ?, ?)"
try:
c = self.conn.cursor()
c.execute(sql, product)
self.conn.commit()
return c.lastrowid
except sqlite3.Error as e:
print(e)
def get_product_by_id(self, product_id):
"""Retrieve a product by its ID."""
sql = "SELECT * FROM products WHERE id = ?"
try:
c = self.conn.cursor()
c.execute(sql, (product_id,))
return c.fetchone()
except sqlite3.Error as e:
print(e)
return None
def get_all_products(self):
"""Retrieve all products."""
sql = "SELECT * FROM products"
try:
c = self.conn.cursor()
c.execute(sql)
return c.fetchall()
except sqlite3.Error as e:
print(e)
return []
def update_product(self, product_id, product_data):
"""Update a product's information."""
sql = "UPDATE products SET name = ?, price = ?, quantity = ? WHERE id = ?"
try:
c = self.conn.cursor()
c.execute(sql, (*product_data, product_id))
self.conn.commit()
except sqlite3.Error as e:
print(e)
def delete_product(self, product_id):
"""Delete a product by its ID."""
sql = "DELETE FROM products WHERE id = ?"
try:
c = self.conn.cursor()
c.execute(sql, (product_id,))
self.conn.commit()
except sqlite3.Error as e:
print(e)
def main():
database = "db/shop.db"
product_db = ProductDatabase(database)
# delete all products
for product in product_db.get_all_products():
product_db.delete_product(product[0])
# name, price, quantity
products = [("Apel", 2.5, 5),
("Banana", 1.5, 10),
("Orange", 3.2, 7)]
for product in products:
product_db.add_product(product)
products = product_db.get_all_products()
print("All products:")
for product in products:
print(product)
# name, price, quantity
product_data = ("Orange", 3.0, 5)
product_db.update_product(3, product_data)
product = product_db.get_product_by_id(1)
print("Updated product:")
print(product)
product_db.delete_product(2)
print("Product deleted")
products = product_db.get_all_products()
print("All products:")
for product in products:
print(product)
if __name__ == "__main__":
main()