Import Sqlite3
Import Sqlite3
class Book:
"""Represents a book entity and its attributes."""
def __init__(self, id=None, title=None, author=None, year=None):
self.id = id
self.title = title
self.author = author
self.year = year
def __str__(self):
return f"ID: {self.id}, Title: {self.title}, Author: {self.author}, Year:
{self.year}"
class DatabaseManager:
"""Manages database connection and operations for books."""
def __init__(self, db_name):
self.db_name = db_name
self.connection = sqlite3.connect(db_name)
self.create_table()
def create_table(self):
"""Creates the books table if it doesn't exist."""
cursor = self.connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER NOT NULL
)
''')
self.connection.commit()
def get_all_books(self):
"""Retrieves all books from the database."""
cursor = self.connection.cursor()
cursor.execute("SELECT id, title, author, year FROM books")
return [Book(*row) for row in cursor.fetchall()]
def close_connection(self):
"""Closes the database connection."""
self.connection.close()
# Example usage
if __name__ == "__main__":
# Initialize database manager
db = DatabaseManager("library.db")
# Update a book
book_to_update = db.get_book_by_id(1)
if book_to_update:
book_to_update.title = "Updated Gatsby"
db.update_book(book_to_update)
# Delete a book
db.delete_book(2)
print("\nAfter deletion:")
for book in db.get_all_books():
print(book)
# Close connection
db.close_connection()