IWS_WS24_clean_architecture/db/db_user.py

89 lines
2.4 KiB
Python
Raw Normal View History

import sqlite3
class UserDatabase:
def __init__(self, db_file):
"""Initialize the UserDatabase with a connection to the SQLite database."""
self.conn = sqlite3.connect(db_file)
def add_user(self, user):
"""Add a new user to the users table and return the new user's id."""
sql = "INSERT INTO users (name, email) VALUES (?, ?)"
try:
c = self.conn.cursor()
c.execute(sql, user)
self.conn.commit()
return c.lastrowid
except sqlite3.Error as e:
print(e)
return None
def get_user_by_id(self, user_id):
"""Retrieve a user by their ID."""
sql = "SELECT * FROM users WHERE id = ?"
try:
c = self.conn.cursor()
c.execute(sql, (user_id,))
return c.fetchone()
except sqlite3.Error as e:
print(e)
return None
def update_user(self, user_id, user_data):
"""Update a user's information."""
sql = "UPDATE users SET name = ?, email = ? WHERE id = ?"
try:
c = self.conn.cursor()
c.execute(sql, (*user_data, user_id))
self.conn.commit()
except sqlite3.Error as e:
print(e)
def delete_user(self, user_id):
"""Delete a user by their ID."""
sql = "DELETE FROM users WHERE id = ?"
try:
c = self.conn.cursor()
c.execute(sql, (user_id,))
self.conn.commit()
except sqlite3.Error as e:
print(e)
def get_all_users(self):
"""Retrieve all users."""
sql = "SELECT * FROM users"
try:
c = self.conn.cursor()
c.execute(sql)
return c.fetchall()
except sqlite3.Error as e:
print(e)
return []
def main():
database = "db/shop.db"
user_db = UserDatabase(database)
# delete all users
for user in user_db.get_all_users():
user_db.delete_user(user[0])
users = [("Michael", "michael@mail.com"),
("Klöara", "klara@mail.com"),
("Arman", "arman@mail.com")]
for user in users:
user_id = user_db.add_user(user)
user = user_db.get_user_by_id(1)
print(f"Retrieved user: {user}")
user_db.update_user(2, ("Klara", "klara@mail.com"))
users = user_db.get_all_users()
for user in users:
print(user)
if __name__ == "__main__":
main()