Logo

dev-resources.site

for different kinds of informations.

Building a Simple SQLite Library Manager in Python

Published at
12/8/2024
Categories
python
sqlite
database
tutorial
Author
blamsa0mine
Categories
4 categories in total
python
open
sqlite
open
database
open
tutorial
open
Author
11 person written this
blamsa0mine
open
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}")
Enter fullscreen mode Exit fullscreen mode

Run this function to initialize the database:

create_library_database()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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? 🚀

sqlite Article's
30 articles in total
Favicon
Android SQLite Crud Tutorial
Favicon
🚀 Building a User Management API with FastAPI and SQLite
Favicon
How to Use SQLite in Vue 3: Complete Guide to Offline-First Web Apps
Favicon
Building a Simple SQLite Library Manager in Python
Favicon
MySQL vs SQLite أيهما أفضل ؟
Favicon
How to setup Ghost in a VPS using Docker, Mailgun and SQLite
Favicon
Java JDBC + IntelliJ + SQLite - A Beginner's Walkthrough
Favicon
Cloudflare D1 and Prisma: Not a Good Combination (For Now)
Favicon
How to Query CSV Files with SQLite
Favicon
Deploy FastAPI application with SQLite on Fly.io
Favicon
How to import excel into sqlite only 1 step
Favicon
PostgreSQL vs. SQLite: read & write in multithreaded environment
Favicon
PostgreSQL vs. SQLite: 멀티스레드 환경에서의 읽기-쓰기
Favicon
Sometimes it's the little things
Favicon
Tauri 2.0 - Sqlite DB - React
Favicon
SQLite Database Recovery
Favicon
Streamlining Your Rails 8 App: Migrating from Postgres to SQLite
Favicon
I still prefer SQLite for little things you know.
Favicon
How to Build Lightweight GraphRAG with SQLite
Favicon
Can You Create a Product That Makes Money with Wasm?
Favicon
Building a cache in Python
Favicon
Building a RESTful API with Laravel 11, A Complete Guide
Favicon
In-Memory Database with SQLite
Favicon
Build your own SQLite, Part 2: Scanning large tables
Favicon
Fundamentos para Web APIs com .NET: Uma Introdução ao Essencial com Entity Framework
Favicon
Multitenant Database Schemas
Favicon
Use SQLite as a Celery broker in Django
Favicon
Build your own SQLite, Part 1: Listing tables
Favicon
Hosting a simple Laravel application using Turso on Laravel Forge
Favicon
Introducing vectorlite: A Fast and Tunable Vector Search Extension for SQLite

Featured ones: