Home Backend Development Python Tutorial Building a Simple SQLite Library Manager in Python

Building a Simple SQLite Library Manager in Python

Dec 10, 2024 pm 02:29 PM

Building a Simple SQLite Library Manager in Python

Building a Simple SQLite Library Manager in Python

Managing data efficiently is a key part of any project, and SQLite makes this task simple and lightweight. In this tutorial, we’ll build a small Python application to manage a library database, allowing you to add and retrieve books with minimal effort.

By the end of this article, you’ll know how to:

  • Create a SQLite database and table.
  • Insert records while preventing duplicates.
  • Retrieve data based on specific criteria.

1. Creating the Database and Table

Let’s start by creating our SQLite database file and defining the books table. Each book will have fields for its title, author, ISBN, publication date, and genre.

import sqlite3
import os

def create_library_database():
    """Creates the library database if it doesn't already exist."""
    db_name = "library.db"

    if not os.path.exists(db_name):
        print(f"Creating database: {db_name}")
        conn = sqlite3.connect(db_name)
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS books (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT,
                author TEXT,
                isbn TEXT UNIQUE,
                published_date DATE,
                genre TEXT
            )
        ''')
        conn.commit()
        conn.close()
    else:
        print(f"Database already exists: {db_name}")
Copy after login

Run this function to initialize the database:

create_library_database()
Copy after login

This will create a library.db file in your project directory, containing a books table with the specified fields.


  1. Inserting Books into the Database

To insert books, we want to ensure that duplicate entries (based on the isbn field) are avoided. Instead of manually checking for duplicates, we’ll use SQLite’s INSERT OR IGNORE statement.

Here’s the function to add books:

def insert_book(book):
    """
    Inserts a book into the database. If a book with the same ISBN already exists,
    the insertion is ignored.
    """
    conn = sqlite3.connect("library.db")
    cursor = conn.cursor()

    try:
        # Insert the book. Ignore the insertion if the ISBN already exists.
        cursor.execute('''
            INSERT OR IGNORE INTO books (title, author, isbn, published_date, genre)
            VALUES (?, ?, ?, ?, ?)
        ''', (book["title"], book["author"], book["isbn"], book["published_date"], book["genre"]))
        conn.commit()

        if cursor.rowcount == 0:
            print(f"The book with ISBN '{book['isbn']}' already exists in the database.")
        else:
            print(f"Book inserted: {book['title']} by {book['author']}")

    except sqlite3.Error as e:
        print(f"Database error: {e}")
    finally:
        conn.close()
Copy after login

This function uses the INSERT OR IGNORE SQL statement to ensure duplicate entries are skipped efficiently.


 3. Adding Some Books

Let’s test the insert_book function by adding some books to our library.

books = [
    {
        "title": "To Kill a Mockingbird",
        "author": "Harper Lee",
        "isbn": "9780061120084",
        "published_date": "1960-07-11",
        "genre": "Fiction"
    },
    {
        "title": "1984",
        "author": "George Orwell",
        "isbn": "9780451524935",
        "published_date": "1949-06-08",
        "genre": "Dystopian"
    },
    {
        "title": "Pride and Prejudice",
        "author": "Jane Austen",
        "isbn": "9781503290563",
        "published_date": "1813-01-28",
        "genre": "Romance"
    }
]

for book in books:
    insert_book(book)
Copy after login

When you run the above code, the books will be added to the database. If you run it again, you’ll see messages like:

The book with ISBN '9780061120084' already exists in the database.
The book with ISBN '9780451524935' already exists in the database.
The book with ISBN '9781503290563' already exists in the database.
Copy after login

4. Retrieving Books

You can easily retrieve data by querying the database. For example, to fetch all books in the library:

def fetch_all_books():
    conn = sqlite3.connect("library.db")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM books")
    rows = cursor.fetchall()
    conn.close()
    return rows

books = fetch_all_books()
for book in books:
    print(book)
Copy after login

Conclusion

With just a few lines of Python, you now have a functional library manager that can insert books while preventing duplicates and retrieve records effortlessly. SQLite’s INSERT OR IGNORE is a powerful feature that simplifies handling constraints, making your code more concise and efficient.

Feel free to expand this project with features like:

  • Searching for books by title or author.
  • Updating book information.
  • Deleting books.

What will you build next? ?

The above is the detailed content of Building a Simple SQLite Library Manager in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article

Hot tools Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Do I Use Beautiful Soup to Parse HTML? How Do I Use Beautiful Soup to Parse HTML? Mar 10, 2025 pm 06:54 PM

How Do I Use Beautiful Soup to Parse HTML?

Image Filtering in Python Image Filtering in Python Mar 03, 2025 am 09:44 AM

Image Filtering in Python

How to Download Files in Python How to Download Files in Python Mar 01, 2025 am 10:03 AM

How to Download Files in Python

How to Use Python to Find the Zipf Distribution of a Text File How to Use Python to Find the Zipf Distribution of a Text File Mar 05, 2025 am 09:58 AM

How to Use Python to Find the Zipf Distribution of a Text File

How to Work With PDF Documents Using Python How to Work With PDF Documents Using Python Mar 02, 2025 am 09:54 AM

How to Work With PDF Documents Using Python

Intro to Flask: Adding a Contact Page Intro to Flask: Adding a Contact Page Feb 28, 2025 am 10:03 AM

Intro to Flask: Adding a Contact Page

How to Cache Using Redis in Django Applications How to Cache Using Redis in Django Applications Mar 02, 2025 am 10:10 AM

How to Cache Using Redis in Django Applications

How to Perform Deep Learning with TensorFlow or PyTorch? How to Perform Deep Learning with TensorFlow or PyTorch? Mar 10, 2025 pm 06:52 PM

How to Perform Deep Learning with TensorFlow or PyTorch?

See all articles