Python and SQLite: Building a Contact Book Exercise

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating the Contact Book
  5. Adding Contacts
  6. Viewing Contacts
  7. Updating Contacts
  8. Deleting Contacts
  9. Conclusion

Introduction

In this tutorial, we will build a contact book application using Python and SQLite. A contact book allows users to store and manage their contacts, including names, phone numbers, and email addresses. By the end of this tutorial, you will have a functional contact book that allows you to add, view, update, and delete contacts.

Prerequisites

Before starting this tutorial, you should have a basic understanding of the Python programming language. Familiarity with SQLite and SQL queries will also be helpful but is not required.

Setup

To follow along with this tutorial, you need to have Python installed on your system. You can download the latest version of Python from the official Python website (https://www.python.org/downloads/). Additionally, we will use the built-in SQLite module, which is included with Python.

Creating the Contact Book

  1. Create a new Python file and name it contact_book.py.
  2. Import the required modules:

    import sqlite3
    
  3. Establish a connection to the SQLite database:

    conn = sqlite3.connect('contact_book.db')
    

    This will create a new SQLite database file called contact_book.db if it doesn’t exist already.

  4. Create a cursor object to execute SQL queries:

    cursor = conn.cursor()
    
  5. Define a function called create_table to create the contact table:

    def create_table():
        cursor.execute('''CREATE TABLE IF NOT EXISTS contacts
                           (id INTEGER PRIMARY KEY AUTOINCREMENT,
                            name TEXT,
                            phone TEXT,
                            email TEXT)''')
    

    The contacts table will have four columns: id, name, phone, and email.

  6. Call the create_table function to create the table:

    create_table()
    
  7. Close the database connection:

    conn.close()
    

    Adding Contacts

  8. Open the contact_book.py file.
  9. Add a function called add_contact to insert a new contact into the database:

    def add_contact(name, phone, email):
        conn = sqlite3.connect('contact_book.db')
        cursor = conn.cursor()
        cursor.execute('''INSERT INTO contacts (name, phone, email)
                           VALUES (?, ?, ?)''', (name, phone, email))
        conn.commit()
        conn.close()
    

    This function takes name, phone, and email as parameters and inserts a new row into the contacts table.

  10. Call the add_contact function with the contact details:

    add_contact('John Doe', '1234567890', '[email protected]')
    

    This will add a new contact to the contact book.

Viewing Contacts

  1. Add a function called view_contacts to retrieve all contacts from the database:

    def view_contacts():
        conn = sqlite3.connect('contact_book.db')
        cursor = conn.cursor()
        cursor.execute('''SELECT * FROM contacts''')
        contacts = cursor.fetchall()
        conn.close()
        return contacts
    

    This function selects all rows from the contacts table and returns them as a list of tuples.

  2. Call the view_contacts function:

    contacts = view_contacts()
    for contact in contacts:
        print(contact)
    

    This will print all the contacts stored in the contact book.

Updating Contacts

  1. Add a function called update_contact to update an existing contact:

    def update_contact(contact_id, new_name, new_phone, new_email):
        conn = sqlite3.connect('contact_book.db')
        cursor = conn.cursor()
        cursor.execute('''UPDATE contacts SET name = ?, phone = ?, email = ?
                           WHERE id = ?''', (new_name, new_phone, new_email, contact_id))
        conn.commit()
        conn.close()
    

    This function takes the contact_id of the contact to be updated, as well as the new name, phone, and email values.

  2. Call the update_contact function with the contact ID and new values:

    update_contact(1, 'Jane Smith', '9876543210', '[email protected]')
    

    This will update the contact with the ID 1 in the contact book.

Deleting Contacts

  1. Add a function called delete_contact to delete a contact:

    def delete_contact(contact_id):
        conn = sqlite3.connect('contact_book.db')
        cursor = conn.cursor()
        cursor.execute('''DELETE FROM contacts WHERE id = ?''', (contact_id,))
        conn.commit()
        conn.close()
    

    This function takes the contact_id of the contact to be deleted.

  2. Call the delete_contact function with the contact ID:

    delete_contact(1)
    

    This will delete the contact with the ID 1 from the contact book.

Conclusion

In this tutorial, we learned how to build a contact book application using Python and SQLite. We covered the basic operations of adding, viewing, updating, and deleting contacts. With the knowledge gained from this tutorial, you can further enhance the functionality of the contact book or apply similar concepts to other projects. Remember to always handle database connections properly and validate user input to ensure data integrity. Happy coding!