import sqlite3
class Book:
"""Represents a book entity and its attributes."""
def __init__(self, id=None, title=None, author=None, year=None):
[Link] = id
[Link] = title
[Link] = author
[Link] = year
def __str__(self):
return f"ID: {[Link]}, Title: {[Link]}, Author: {[Link]}, Year:
{[Link]}"
class DatabaseManager:
"""Manages database connection and operations for books."""
def __init__(self, db_name):
self.db_name = db_name
[Link] = [Link](db_name)
self.create_table()
def create_table(self):
"""Creates the books table if it doesn't exist."""
cursor = [Link]()
[Link]('''
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER NOT NULL
)
''')
[Link]()
def add_book(self, book):
"""Adds a new book to the database."""
sql = "INSERT INTO books (title, author, year) VALUES (?, ?, ?)"
params = ([Link], [Link], [Link])
cursor = [Link]()
[Link](sql, params)
[Link]()
[Link] = [Link]
return book
def get_all_books(self):
"""Retrieves all books from the database."""
cursor = [Link]()
[Link]("SELECT id, title, author, year FROM books")
return [Book(*row) for row in [Link]()]
def get_book_by_id(self, book_id):
"""Retrieves a single book by its ID."""
cursor = [Link]()
[Link]("SELECT * FROM books WHERE id = ?", (book_id,))
row = [Link]()
return Book(*row) if row else None
def update_book(self, book):
"""Updates an existing book in the database."""
sql = "UPDATE books SET title = ?, author = ?, year = ? WHERE id = ?"
params = ([Link], [Link], [Link], [Link])
cursor = [Link]()
[Link](sql, params)
[Link]()
return [Link] > 0
def delete_book(self, book_id):
"""Deletes a book from the database."""
cursor = [Link]()
[Link]("DELETE FROM books WHERE id = ?", (book_id,))
[Link]()
return [Link] > 0
def close_connection(self):
"""Closes the database connection."""
[Link]()
# Example usage
if __name__ == "__main__":
# Initialize database manager
db = DatabaseManager("[Link]")
# Add new books
book1 = Book(None, "The Great Gatsby", "F. Scott Fitzgerald", 1925)
book2 = Book(None, "1984", "George Orwell", 1949)
db.add_book(book1)
db.add_book(book2)
# Display all books
print("All books:")
for book in db.get_all_books():
print(book)
# 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)
# Get and display updated book
print("\nUpdated book:")
print(db.get_book_by_id(1))
# Delete a book
db.delete_book(2)
print("\nAfter deletion:")
for book in db.get_all_books():
print(book)
# Close connection
db.close_connection()