24 Oct 2024

Creating a Contact Book App with Python and SQLite

In this tutorial, we'll guide you through the process of creating a contact book application using Python and SQLite. This application serves as a valuable tool for efficiently managing your contacts, whether it's for personal or professional purposes.

Upon completion of this tutorial, you'll have a fully functional Python application at your disposal. This application empowers you to effortlessly perform tasks like adding, viewing, updating, and deleting contacts.

Shall we get started? 🚀

  1. Prerequisites
  2. Setting Up the Project
  3. Creating the Database
  4. Designing the User Interface
  5. Implementing CRUD Operations
    1. Adding Contacts
    2. Viewing Contacts
    3. Updating Contacts
    4. Deleting Contacts
  6. Conclusion

The contact book app will be a command-line application that utilizes the SQLite database to store contact information. We'll leverage the power of Python to interact with the database, handle user input, and display information. The app will have basic CRUD (Create, Read, Update, Delete) functionalities for managing contacts.

Prerequisites

To follow along with this tutorial, you should have the following prerequisites:

Setting Up the Project

Let's start by setting up the project directory and creating the main Python script file.

1. Create a new directory for the project. You can name it something like "ContactBookApp."
2. Inside the project directory, create a new Python file named "contact_book.py."

Creating the Database

We'll use the SQLite database for storing our contact information. Python comes with built-in support for SQLite, making it an excellent choice for this simple application.

First, we need to import the SQLite library and connect to the database.

# contact_book.py

import sqlite3

def create_connection(database):
    conn = None
    try:
        conn = sqlite3.connect(database)
        print("Connected to database successfully!")
        return conn
    except sqlite3.Error as e:
        print(e)
        return None

Next, we'll create a table called "contacts" to store our contact information.

def create_table(conn):
    try:
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS contacts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                phone TEXT NOT NULL,
                email TEXT NOT NULL
            )
        ''')
        print("Table created successfully!")
    except sqlite3.Error as e:
        print(e)

if __name__ == "__main__":
    database = "contact_book.db"
    conn = create_connection(database)
    if conn is not None:
        create_table(conn)
        conn.close()

The above code defines a function create_table that creates a table called "contacts" with four columns: "id" (primary key), "name," "phone," and "email." The primary key will be auto-incremented for each new contact, ensuring a unique identifier for each record.

When you run the script, it will create a new SQLite database file named "contact_book.db" and a table named "contacts" inside it.

Designing the User Interface

Since our app is a command-line application, we'll use simple text-based menus to interact with the user. The user will be able to choose from options such as "Add Contact," "View Contacts," "Update Contact," "Delete Contact," and "Exit."

# contact_book.py

def print_menu():
    print("\n--- Contact Book App ---")
    print("1. Add Contact")
    print("2. View Contacts")
    print("3. Update Contact")
    print("4. Delete Contact")
    print("5. Exit")

def get_user_choice():
    try:
        choice = int(input("Enter your choice: "))
        return choice
    except ValueError:
        print("Invalid choice. Please enter a valid number.")
        return -1

if __name__ == "__main__":
    # ... (previous code)
    
    while True:
        print_menu()
        choice = get_user_choice()
        
        if choice == 1:
            # Add Contact
        elif choice == 2:
            # View Contacts
        elif choice == 3:
            # Update Contact
        elif choice == 4:
            # Delete Contact
        elif choice == 5:
            print("Exiting the Contact Book App. Goodbye!")
            break
        else:
            print("Invalid choice. Please select a valid option.")

With the basic user interface set up, let's move on to implementing the CRUD operations.

Implementing CRUD Operations

CRUD operations are essential for managing contacts in our app. We'll implement the following functions: "add_contact," "view_contacts," "update_contact," and "delete_contact."

Adding Contacts

To add a contact, we need to prompt the user for the contact's name, phone number, and email, and then insert this information into the "contacts" table.

# contact_book.py

def add_contact(conn, name, phone, email):
    try:
        cursor = conn.cursor()
        cursor.execute('''
            INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)
        ''', (name, phone, email))
        conn.commit()
        print("Contact added successfully!")
    except sqlite3.Error as e:
        print(e)

# Inside the while loop:

if choice == 1:
    print("\n--- Add Contact ---")
    name = input("Enter the contact's name: ")
    phone = input("Enter the contact's phone number: ")
    email = input("Enter the contact's email address: ")
    add_contact(conn, name, phone, email)

Viewing Contacts

To view all contacts in the contact book, we'll retrieve the records from the "contacts" table and display them.

# contact_book.py

def view_contacts(conn):
    try:
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM contacts")
        contacts = cursor.fetchall()
        if not contacts:
            print("No contacts found.")
        else:
            print("\n--- All Contacts ---")
            for contact in contacts:
                print(f"ID: {contact[0]}, Name: {contact[1]}, Phone: {contact[2]}, Email: {contact[3]}")
    except sqlite3.Error as e:
        print(e)

# Inside the while loop:

elif choice == 2:
    view_contacts(conn)

Updating Contacts

To update a contact, we'll first display all contacts and ask the user to select the ID of the contact they want to update. Then, we'll prompt the user for the new name, phone number, and email and update the corresponding record in the database.

# contact_book.py

def update_contact(conn, contact_id, name, phone, email):
    try:
        cursor = conn.cursor()
        cursor.execute('''
            UPDATE contacts SET name = ?, phone =

 ?, email = ? WHERE id = ?
        ''', (name, phone, email, contact_id))
        conn.commit()
        print("Contact updated successfully!")
    except sqlite3.Error as e:
        print(e)

# Inside the while loop:

elif choice == 3:
    view_contacts(conn)
    contact_id = int(input("Enter the ID of the contact to update: "))
    name = input("Enter the new name: ")
    phone = input("Enter the new phone number: ")
    email = input("Enter the new email address: ")
    update_contact(conn, contact_id, name, phone, email)

Deleting Contacts

To delete a contact, we'll again display all contacts and ask the user to select the ID of the contact they want to delete. We'll then delete the corresponding record from the database.

# contact_book.py

def delete_contact(conn, contact_id):
    try:
        cursor = conn.cursor()
        cursor.execute("DELETE FROM contacts WHERE id = ?", (contact_id,))
        conn.commit()
        print("Contact deleted successfully!")
    except sqlite3.Error as e:
        print(e)

# Inside the while loop:

elif choice == 4:
    view_contacts(conn)
    contact_id = int(input("Enter the ID of the contact to delete: "))
    delete_contact(conn, contact_id)

Conclusion

Well done on successfully creating a contact book application using Python and SQLite! This application allows you to seamlessly perform tasks like adding, viewing, updating, and deleting contacts right from the command line. This provides a straightforward yet efficient method for managing your contacts.

To further enhance the app's capabilities, you might want to consider implementing a search functionality. This feature would enable users to quickly locate specific contacts based on various criteria.

Furthermore, consider expanding the contact details section to include additional information like addresses, birthdays, or notes. This would offer users a more comprehensive overview of their contacts.

For an improved user experience, contemplate developing a graphical user interface (GUI) using libraries such as Tkinter or PyQt. A GUI would provide a more intuitive and visually appealing interface for interacting with the application.

Keep up the great work! If you need any further assistance or advice, feel free to ask. 👍🏽

You may also like

Creating a responsive contact form with HTML, CSS, and JavaScript

Learn how to create a responsive contact form with HTML, CSS, and Ja...

Continue reading

Building a Command-Line Weather App with Python

In this blog, we explored the process of building a command-line wea...

Continue reading

Developing a Simple Calculator App with Python and PyQt

In this tutorial, we will guide you through the process of developin...

Continue reading