The user wants a Python program to manage contacts using a SQLite database.
This implies the following features:
- Database Connection and Setup: Connect to a SQLite file (or create one) and create a table if it doesn't exist.
- CRUD Operations:
- Create: Add a new contact.
- Read: View all contacts or search for a specific one.
- Update: Modify an existing contact.
- Delete: Remove a contact.
- User Interface (CLI): A simple command-line interface to interact with the user and trigger these functions.
Step 1: Database Setup
- Use the
sqlite3 module (standard library).
- Table schema:
id (INTEGER PRIMARY KEY), name (TEXT), phone (TEXT), email (TEXT).
Step 2: Function Definitions
init_db(): Connects and creates the table.
add_contact(name, phone, email): INSERT statement.
view_contacts(): SELECT * statement.
update_contact(contact_id, ...): UPDATE statement.
delete_contact(contact_id): DELETE statement.
Step 3: User Interface Loop
- A
while True loop.
- Print a menu (1. Add, 2. View, 3. Update, 4. Delete, 5. Exit).
- Get user input.
- Call the appropriate function based on input.
- Handle invalid inputs (try/except or simple checks).
Refining the Code Structure:
- It's best practice to use a context manager (
with sqlite3.connect(...)) or ensure the connection is closed properly, but for a continuous CLI app, opening a global connection or opening/closing per operation is acceptable. Opening per operation is safer against corruption if the script crashes, but a class-based approach or passing a connection object is cleaner. Let's stick to a functional approach where connection is established per transaction for simplicity and robustness in a beginner-friendly script. Or better, a DatabaseManager class.
- Actually, for a simple script, functions that open and close connections are often easier to read for beginners.
Drafting the Code:
-
Import: import sqlite3
-
Constants: DB_NAME = "contacts.db"
-
Function initialize_db():
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS contacts (...)''')
conn.commit()
conn.close()
-
Function add_contact():
Get inputs inside the function or pass arguments? Better to separate logic from UI. The main loop gets inputs, passes them to the function.
-
Function view_contacts():
Fetch all, print formatted.
-
Function update_contact():
Need ID. Ask which fields to update? Or just update all? Simple approach: Ask for ID, then new name/phone/email.
-
Function delete_contact():
Need ID.
Improving the CLI:
- Use a main function
menu().
- Add error handling for database operations.
Code Structure Plan:
- Imports.
- Database initialization function.
- Helper functions (add, get, update, delete).
- Main menu loop.
- Entry point check (
if __name__ == "__main__":).
Self-Correction/Refinement:
- Should I use an ORM like SQLAlchemy? No, the prompt asks for "SQLite database", implying direct SQL usage is preferred for simplicity and standard library use.
- Make sure to handle the case where the user tries to delete/update an ID that doesn't exist.
- Format the output nicely (e.g., using f-strings).
Let's write the actual code logic.
Schema:
id INTEGER PRIMARY KEY AUTOINCREMENT
name TEXT NOT NULL
phone TEXT
email TEXT
Update Logic:
If I update, I usually want to keep old values if the user leaves the input blank.
Logic: new_name = input(...) or old_name (This is a nice touch).
Let's assemble the solution.
Here is a complete, executable Python program that uses the built-in sqlite3 library to manage contacts. No external installation is required.
Features
- Add Contact: Create a new contact with name, phone, and email.
- View Contacts: Display all contacts in a formatted list.
- Update Contact: Modify details of an existing contact using its ID.
- Delete Contact: Remove a contact using its ID.
- Persistent Storage: Data is saved in a local file
contacts.db.
The Python Program
You can save this code in a file named contact_manager.py and run it.
import sqlite3
import sys
# The name of the database file
DB_NAME = "contacts.db"
def initialize_db():
"""
Connects to the database and creates the 'contacts' table
if it does not already exist.
"""
try:
# Connect creates the file if it doesn't exist
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
# Create table with columns: id, name, phone, email
cursor.execute("""
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
phone TEXT,
email TEXT
)
""")
conn.commit()
except sqlite3.Error as e:
print(f"Error initializing database: {e}")
def add_contact(name, phone, email):
"""Inserts a new contact into the database."""
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)",
(name, phone, email)
)
conn.commit()
print(f"\nSuccess: Contact '{name}' added.")
except sqlite3.Error as e:
print(f"Error adding contact: {e}")
def view_contacts():
"""Fetches and displays all contacts."""
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM contacts")
rows = cursor.fetchall()
print("\n--- Contact List ---")
if not rows:
print("No contacts found.")
else:
print(f"{'ID':<5} {'Name':<20} {'Phone':<15} {'Email':<25}")
print("-" * 65)
for row in rows:
# row[0]=id, row[1]=name, row[2]=phone, row[3]=email
print(f"{row[0]:<5} {row[1]:<20} {row[2]:<15} {row[3]:<25}")
print("-" * 65)
except sqlite3.Error as e:
print(f"Error fetching contacts: {e}")
def update_contact(contact_id, name, phone, email):
"""Updates an existing contact based on ID."""
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
# Check if ID exists first
cursor.execute("SELECT id FROM contacts WHERE id = ?", (contact_id,))
if not cursor.fetchone():
print(f"\nError: Contact with ID {contact_id} not found.")
return
cursor.execute(
"UPDATE contacts SET name = ?, phone = ?, email = ? WHERE id = ?",
(name, phone, email, contact_id)
)
conn.commit()
print(f"\nSuccess: Contact ID {contact_id} updated.")
except sqlite3.Error as e:
print(f"Error updating contact: {e}")
def delete_contact(contact_id):
"""Deletes a contact based on ID."""
try:
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
# Check if ID exists
cursor.execute("SELECT name FROM contacts WHERE id = ?", (contact_id,))
contact = cursor.fetchone()
if not contact:
print(f"\nError: Contact with ID {contact_id} not found.")
else:
cursor.execute("DELETE FROM contacts WHERE id = ?", (contact_id,))
conn.commit()
print(f"\nSuccess: Contact '{contact[0]}' deleted.")
except sqlite3.Error as e:
print(f"Error deleting contact: {e}")
def get_menu_choice():
"""Displays the menu and gets user input."""
print("\n=== Contact Manager ===")
print("1. Add Contact")
print("2. View All Contacts")
print("3. Update Contact")
print("4. Delete Contact")
print("5. Exit")
while True:
choice = input("Enter choice (1-5): ").strip()
if choice in ['1', '2', '3', '4', '5']:
return choice
print("Invalid choice. Please try again.")
def main():
initialize_db()
while True:
choice = get_menu_choice()
if choice == '1':
name = input("Enter Name: ").strip()
phone = input("Enter Phone: ").strip()
email = input("Enter Email: ").strip()
if name:
add_contact(name, phone, email)
else:
print("Error: Name cannot be empty.")
elif choice == '2':
view_contacts()
elif choice == '3':
try:
c_id = int(input("Enter Contact ID to update: "))
print("(Leave blank to keep current value)")
# We need to fetch current values to make updating easier,
# but for simplicity we ask for all inputs.
# Ideally, you'd fetch the row and pre-fill or skip blanks.
name = input("Enter new Name: ").strip()
phone = input("Enter new Phone: ").strip()
email = input("Enter new Email: ").strip()
update_contact(c_id, name, phone, email)
except ValueError:
print("Error: ID must be a number.")
elif choice == '4':
try:
c_id = int(input("Enter Contact ID to delete: "))
delete_contact(c_id)
except ValueError:
print("Error: ID must be a number.")
elif choice == '5':
print("Exiting program. Goodbye!")
sys.exit()
if __name__ == "__main__":
main()
How it works
sqlite3 Module: We use Python's standard library to interact with the SQLite database. This does not require pip install.
initialize_db(): This function runs every time the script starts. It connects to contacts.db (creating the file if it's missing) and creates the table structure if it doesn't exist yet.
- Context Managers (
with ...): We use with sqlite3.connect(...) as conn:. This ensures that the database connection is automatically closed even if errors occur, preventing file corruption.
- Parameterized Queries (
?): You will notice queries like VALUES (?, ?, ?). This is crucial for security (preventing SQL Injection) and stability (handling names like O'Connor correctly).
- Main Loop: The
while True loop in the main() function keeps the program running, presenting the menu repeatedly until the user chooses to Exit.