0% found this document useful (0 votes)
5 views2 pages

Import Sqlite3

The document defines a Python program that manages a book database using SQLite. It includes a Book class to represent book entities and a DatabaseManager class to handle database operations such as adding, retrieving, updating, and deleting books. The program demonstrates its functionality with example usage, including adding books, updating a book, and displaying all books.

Uploaded by

n.moha760
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Import Sqlite3

The document defines a Python program that manages a book database using SQLite. It includes a Book class to represent book entities and a DatabaseManager class to handle database operations such as adding, retrieving, updating, and deleting books. The program demonstrates its functionality with example usage, including adding books, updating a book, and displaying all books.

Uploaded by

n.moha760
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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 add_book(self, book):


"""Adds a new book to the database."""
sql = "INSERT INTO books (title, author, year) VALUES (?, ?, ?)"
params = (book.title, book.author, book.year)
cursor = self.connection.cursor()
cursor.execute(sql, params)
self.connection.commit()
book.id = cursor.lastrowid
return book

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 get_book_by_id(self, book_id):


"""Retrieves a single book by its ID."""
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM books WHERE id = ?", (book_id,))
row = cursor.fetchone()
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 = (book.title, book.author, book.year, book.id)
cursor = self.connection.cursor()
cursor.execute(sql, params)
self.connection.commit()
return cursor.rowcount > 0

def delete_book(self, book_id):


"""Deletes a book from the database."""
cursor = self.connection.cursor()
cursor.execute("DELETE FROM books WHERE id = ?", (book_id,))
self.connection.commit()
return cursor.rowcount > 0

def close_connection(self):
"""Closes the database connection."""
self.connection.close()

# Example usage
if __name__ == "__main__":
# Initialize database manager
db = DatabaseManager("library.db")

# 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()

You might also like