IWS_WS24_clean_architecture/db/db_setup.py

66 lines
1.8 KiB
Python

import sqlite3
def create_connection(db_file):
"""Create a database connection to the SQLite database specified by db_file."""
conn = None
try:
conn = sqlite3.connect(db_file)
print(f"Connected to {db_file}")
except sqlite3.Error as e:
print(e)
return conn
def create_table(conn, create_table_sql):
"""Create a table from the create_table_sql statement."""
try:
c = conn.cursor()
c.execute(create_table_sql)
print("Table created successfully")
except sqlite3.Error as e:
print(e)
def delete_table(conn, table_name):
"""Delete a table specified by table_name."""
try:
c = conn.cursor()
c.execute(f"DROP TABLE IF EXISTS {table_name}")
print(f"Table {table_name} deleted successfully")
except sqlite3.Error as e:
print(e)
def main():
database = "db/shop.db"
sql_user_table = """CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL
)"""
sql_product_table = """CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price REAL NOT NULL,
quantity INTEGER NOT NULL
)"""
sql_cart_table = """CREATE TABLE IF NOT EXISTS cart (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (product_id) REFERENCES products (id)
)"""
conn = create_connection(database)
if conn is not None:
create_table(conn, sql_user_table)
create_table(conn, sql_product_table)
create_table(conn, sql_cart_table)
else:
print("Error! Cannot create the database connection.")
if __name__ == '__main__':
main()