Creating a contact manager
The user asked me to write a Python program to manage contacts using a SQLite database. They want the code to include basic CRUD operations and a simple command-line interface (CLI) menu. For the database, I plan to create a contacts.db file and a table with fields like id, name, phone, and email. I'll implement functions for initializing the database, adding, listing, searching, updating, and deleting contacts. Using the standard library will help keep it straightforward. Let's get started on the code!Implementing with clarity
I want to keep the code clear without overexplaining, so I'll add light comments to help guide the user through the program. It might be a good idea to include instructions on how to run the program as well. This way, users will have the information they need without feeling overwhelmed. I’m determined to keep it concise yet informative, making sure it serves its purpose effectively. Let’s go ahead and implement that! Below is a complete, self-contained Python script that manages contacts in a SQLite database using a simple text-based menu.
It supports:
- Creating the database/table automatically
- Adding contacts
- Viewing all contacts
- Searching contacts (by name, phone, or email)
- Updating a contact
- Deleting a contact
Save as contacts.py and run with python contacts.py.
import sqlite3
from contextlib import closing
DB_PATH = "contacts.db"
def get_connection():
"""Return a connection to the SQLite database."""
return sqlite3.connect(DB_PATH)
def init_db():
"""Create the contacts table if it doesn't exist."""
with get_connection() as conn:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
phone TEXT,
email TEXT,
address TEXT
)
"""
)
conn.commit()
def add_contact(name, phone=None, email=None, address=None):
with get_connection() as conn:
conn.execute(
"""
INSERT INTO contacts (name, phone, email, address)
VALUES (?, ?, ?, ?)
""",
(name, phone, email, address),
)
conn.commit()
def list_contacts():
with get_connection() as conn, closing(conn.cursor()) as cur:
cur.execute("SELECT id, name, phone, email, address FROM contacts ORDER BY name")
return cur.fetchall()
def search_contacts(keyword):
kw = f"%{keyword}%"
with get_connection() as conn, closing(conn.cursor()) as cur:
cur.execute(
"""
SELECT id, name, phone, email, address
FROM contacts
WHERE name LIKE ?
OR phone LIKE ?
OR email LIKE ?
ORDER BY name
""",
(kw, kw, kw),
)
return cur.fetchall()
def get_contact(contact_id):
with get_connection() as conn, closing(conn.cursor()) as cur:
cur.execute(
"SELECT id, name, phone, email, address FROM contacts WHERE id = ?",
(contact_id,),
)
return cur.fetchone()
def update_contact(contact_id, name=None, phone=None, email=None, address=None):
"""Update only the fields that are not None."""
fields = []
values = []
if name is not None:
fields.append("name = ?")
values.append(name)
if phone is not None:
fields.append("phone = ?")
values.append(phone)
if email is not None:
fields.append("email = ?")
values.append(email)
if address is not None:
fields.append("address = ?")
values.append(address)
if not fields:
return # nothing to update
values.append(contact_id)
with get_connection() as conn:
conn.execute(
f"UPDATE contacts SET {', '.join(fields)} WHERE id = ?",
values,
)
conn.commit()
def delete_contact(contact_id):
with get_connection() as conn:
conn.execute("DELETE FROM contacts WHERE id = ?", (contact_id,))
conn.commit()
# --------- CLI Interface ----------
def input_optional(prompt):
value = input(prompt).strip()
return value if value else None
def print_contact_row(row):
cid, name, phone, email, address = row
print(f"[{cid}] {name}")
if phone:
print(f" Phone: {phone}")
if email:
print(f" Email: {email}")
if address:
print(f" Address: {address}")
def menu_add_contact():
print("\n=== Add Contact ===")
name = input("Name (required): ").strip()
if not name:
print("Name is required. Contact not added.")
return
phone = input_optional("Phone: ")
email = input_optional("Email: ")
address = input_optional("Address: ")
add_contact(name, phone, email, address)
print("Contact added.")
def menu_list_contacts():
print("\n=== All Contacts ===")
rows = list_contacts()
if not rows:
print("No contacts found.")
return
for row in rows:
print_contact_row(row)
def menu_search_contacts():
print("\n=== Search Contacts ===")
keyword = input("Enter keyword (name, phone, or email): ").strip()
if not keyword:
print("No keyword entered.")
return
rows = search_contacts(keyword)
if not rows:
print("No matching contacts found.")
return
for row in rows:
print_contact_row(row)
def menu_update_contact():
print("\n=== Update Contact ===")
try:
cid = int(input("Enter contact ID to update: ").strip())
except ValueError:
print("Invalid ID.")
return
contact = get_contact(cid)
if not contact:
print("Contact not found.")
return
print("Current values:")
print_contact_row(contact)
print("\nLeave field blank to keep current value.")
new_name = input_optional("New name: ")
new_phone = input_optional("New phone: ")
new_email = input_optional("New email: ")
new_address = input_optional("New address: ")
# Use current values if no new values were provided
_, cur_name, cur_phone, cur_email, cur_address = contact
update_contact(
cid,
name=new_name or cur_name,
phone=new_phone or cur_phone,
email=new_email or cur_email,
address=new_address or cur_address,
)
print("Contact updated.")
def menu_delete_contact():
print("\n=== Delete Contact ===")
try:
cid = int(input("Enter contact ID to delete: ").strip())
except ValueError:
print("Invalid ID.")
return
contact = get_contact(cid)
if not contact:
print("Contact not found.")
return
print("You are about to delete:")
print_contact_row(contact)
confirm = input("Are you sure? (y/N): ").strip().lower()
if confirm == "y":
delete_contact(cid)
print("Contact deleted.")
else:
print("Deletion canceled.")
def main_menu():
init_db()
while True:
print("\n===== Contact Manager =====")
print("1. Add contact")
print("2. List all contacts")
print("3. Search contacts")
print("4. Update contact")
print("5. Delete contact")
print("0. Exit")
choice = input("Choose an option: ").strip()
if choice == "1":
menu_add_contact()
elif choice == "2":
menu_list_contacts()
elif choice == "3":
menu_search_contacts()
elif choice == "4":
menu_update_contact()
elif choice == "5":
menu_delete_contact()
elif choice == "0":
print("Goodbye.")
break
else:
print("Invalid option. Please try again.")
if __name__ == "__main__":
main_menu()
If you want a variant (e.g., using command-line arguments instead of an interactive menu, or adding fields like birthday/tags), tell me your preferred interface and I’ll adapt the code.