Library management system with SQLite and Python
Learn how to build a complete library management system with Python and SQLite. Step-by-step tutorial covering database creation, tables, CRUD functions, SQL queries, interactive menu, and security best practices.
SQLite is a relational database that adapts well to library management systems because it's lightweight, fast, and easy to configure. It can be used to efficiently manage information about books, users, and loans. Below is a structured approach to creating this system.
Database Schema Definition
Books Table:
Book ID (integer, primary key)
Title (text)
Author (text)
Publisher (text)
Publication Year (integer)
ISBN (text)
Users Table:
User ID (integer, primary key)
First Name (text)
Last Name (text)
Address (text)
Email (text)
Phone (text)
Loans Table:
Loan ID (integer, primary key)
Book ID (integer, foreign key)
User ID (integer, foreign key)
Loan Date (text)
Return Date (text)
Database and Tables Creation Example
Using the sqlite3 library in Python:
import sqlite3 # Connect to the database or create a new one conn = sqlite3.connect('library.db') # Create the 'books' table conn.execute('''CREATE TABLE IF NOT EXISTS books ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT NOT NULL, publisher TEXT, publication_year INTEGER, isbn TEXT)''') # Create the 'users' table conn.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, first_name TEXT NOT NULL, last_name TEXT, address TEXT, email TEXT, phone TEXT)''') # Create the 'loans' table conn.execute('''CREATE TABLE IF NOT EXISTS loans ( id INTEGER PRIMARY KEY, book_id INTEGER NOT NULL, user_id INTEGER NOT NULL, loan_date TEXT NOT NULL, return_date TEXT, FOREIGN KEY(book_id) REFERENCES books(id), FOREIGN KEY(user_id) REFERENCES users(id))''') # Close the connection conn.close()
Inserting Data into the Database
Example of how to add a book to the books table:
# Connect to the database conn = sqlite3.connect('library.db') # Insert a new book conn.execute('''INSERT INTO books (title, author, publisher, publication_year, isbn) VALUES (?, ?, ?, ?, ?)''', ('The Lord of the Rings', 'J.R.R. Tolkien', 'Martins Fontes Publisher', 1954, '9788578270691')) # Save the changes conn.commit() conn.close()
Querying Data from the Database
Example of how to list all registered books:
# Connect to the database conn = sqlite3.connect('library.db') # Select all books books = conn.execute('SELECT * FROM books').fetchall() # Display the books for book in books: print(book) conn.close()
Specific Query: Books Currently on Loan
Below is an example query to display books that are currently on loan:
# Connect to the database conn = sqlite3.connect('library.db') # Query books on loan query = ''' SELECT books.title, users.first_name, users.last_name, loans.loan_date FROM books INNER JOIN loans ON books.id = loans.book_id INNER JOIN users ON users.id = loans.user_id WHERE loans.return_date IS NULL ''' books_on_loan = conn.execute(query).fetchall() # Display the results for record in books_on_loan: print(f"Book: {record[0]}, User: {record[1]} {record[2]}, Loan Date: {record[3]}") conn.close()
Best Practices
Data Validation: Before inserting data into the database, validate inputs to avoid errors or inconsistencies.
Parameterized SQL: Use placeholders (
?) to prevent SQL injection attacks.Database Backup: Periodically make backups to prevent data loss.
With this structure, you'll have a functional library management system using Python and SQLite. This is just the starting point — additional features like graphical interfaces or APIs can be added to enhance the system.
Python Functions to Interact with the Database
Here is the formatted code for the functions to interact with the SQLite database for the library management system:
import sqlite3 # Function to connect to the database def connect(): conn = sqlite3.connect('library.db') return conn # Function to insert a new book into the "books" table def insert_book(title, author, publisher, publication_year, isbn): conn = connect() conn.execute("INSERT INTO books (title, author, publisher, publication_year, isbn) VALUES (?, ?, ?, ?, ?)", (title, author, publisher, publication_year, isbn)) conn.commit() conn.close() # Function to insert a new user into the "users" table def insert_user(first_name, last_name, address, email, phone): conn = connect() conn.execute("INSERT INTO users (first_name, last_name, address, email, phone) VALUES (?, ?, ?, ?, ?)", (first_name, last_name, address, email, phone)) conn.commit() conn.close() # Function to insert a new loan into the "loans" table def insert_loan(book_id, user_id, loan_date, return_date): conn = connect() conn.execute("INSERT INTO loans (book_id, user_id, loan_date, return_date) VALUES (?, ?, ?, ?)", (book_id, user_id, loan_date, return_date)) conn.commit() conn.close() # Function to retrieve all currently loaned books def get_books_on_loan(): conn = connect() result = conn.execute(""" SELECT books.title, users.first_name, users.last_name, loans.loan_date, loans.return_date FROM books INNER JOIN loans ON books.id = loans.book_id INNER JOIN users ON users.id = loans.user_id WHERE loans.return_date IS NULL """).fetchall() conn.close() return result # Function to update the return date of a loan def update_loan_return_date(loan_id, return_date): conn = connect() conn.execute("UPDATE loans SET return_date = ? WHERE id = ?", (return_date, loan_id)) conn.commit() conn.close()
Interactive Menu to Interact with the Functions
Here's the interactive menu that allows you to execute the above functions:
# Import the functions created earlier from database import * # Define the function to display the menu and receive user input def show_menu(): print("\nLibrary Management System") print("Select an option:") print("1. Insert a new book") print("2. Insert a new user") print("3. Make a loan") print("4. Update a loan's return date") print("5. Display all currently loaned books") print("0. Exit") return input("Enter the number of the desired option: ") # Main program loop while True: choice = show_menu() if choice == "1": title = input("Enter the book title: ") author = input("Enter the book author: ") publisher = input("Enter the book publisher: ") year = input("Enter the publication year: ") isbn = input("Enter the book ISBN: ") insert_book(title, author, publisher, year, isbn) print("Book inserted successfully!") elif choice == "2": first_name = input("Enter the user's first name: ") last_name = input("Enter the user's last name: ") address = input("Enter the user's address: ") email = input("Enter the user's email address: ") phone = input("Enter the user's phone number: ") insert_user(first_name, last_name, address, email, phone) print("User inserted successfully!") elif choice == "3": book_id = input("Enter the book ID: ") user_id = input("Enter the user ID: ") loan_date = input("Enter the loan date (format: YYYY-MM-DD): ") insert_loan(book_id, user_id, loan_date, None) print("Loan completed successfully!") elif choice == "4": loan_id = input("Enter the loan ID: ") return_date = input("Enter the new return date (format: YYYY-MM-DD): ") update_loan_return_date(loan_id, return_date) print("Return date updated successfully!") elif choice == "5": books_on_loan = get_books_on_loan() print("\nBooks currently on loan:") for book in books_on_loan: print(f"Title: {book[0]}, User: {book[1]} {book[2]}, Loan Date: {book[3]}, Return Date: {book[4]}") elif choice == "0": print("Exiting the system. Goodbye!") break else: print("Invalid option. Please select a valid option.")
Explanation
Structure:
The menu presents options for each implemented functionality.
Input prompts are used to collect necessary data for each operation.
Functions encapsulate database interactions.
Ease of Use:
The modular structure allows for easy expansion with new features.
Provides clear interaction with the library management system.
Security Practices:
?placeholders in SQL statements prevent SQL injection.Database connections are opened and closed in each function, keeping the database secure.
📄 Source: https://www.usandopy.com/en/article/sistema-de-gerenciamento-de-biblioteca-com-sqlite-e-python/