import sqlite3
def init_db():
"""Initialize the database and create the contacts table if it doesn't exist."""
conn = sqlite3.connect('contacts.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
phone TEXT,
email TEXT
)
''')
conn.commit()
conn.close()
def add_contact():
"""Add a new contact to the database."""
name = input("Enter name: ").strip()
if not name:
print("Name is required.")
return
phone = input("Enter phone: ").strip()
email = input("Enter email: ").strip()
conn = sqlite3.connect('contacts.db')
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)", (name, phone, email))
conn.commit()
print("Contact added successfully.")
except sqlite3.IntegrityError:
print("Contact with this name already exists.")
finally:
conn.close()
def view_contacts():
"""View all contacts in the database."""
conn = sqlite3.connect('contacts.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM contacts ORDER BY name")
rows = cursor.fetchall()
conn.close()
if rows:
print("\n--- All Contacts ---")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Phone: {row[2]}, Email: {row[3]}")
else:
print("No contacts found.")
def search_contact():
"""Search for contacts by name (partial match)."""
search_term = input("Enter name to search: ").strip()
if not search_term:
print("Search term is required.")
return
conn = sqlite3.connect('contacts.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM contacts WHERE name LIKE ? ORDER BY name", (f"%{search_term}%",))
rows = cursor.fetchall()
conn.close()
if rows:
print("\n--- Search Results ---")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Phone: {row[2]}, Email: {row[3]}")
else:
print("No contacts found matching the search term.")
def update_contact():
"""Update an existing contact."""
old_name = input("Enter the current name of the contact: ").strip()
if not old_name:
print("Name is required.")
return
conn = sqlite3.connect('contacts.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM contacts WHERE name=?", (old_name,))
contact = cursor.fetchone()
if contact:
new_name = input(f"New name [{contact[1]}]: ").strip() or contact[1]
new_phone = input(f"New phone [{contact[2]}]: ").strip() or contact[2]
new_email = input(f"New email [{contact[3]}]: ").strip() or contact[3]
try:
cursor.execute(
"UPDATE contacts SET name=?, phone=?, email=? WHERE name=?",
(new_name, new_phone, new_email, old_name)
)
conn.commit()
print("Contact updated successfully.")
except sqlite3.IntegrityError:
print("Update failed: A contact with the new name already exists.")
else:
print("Contact not found.")
conn.close()
def delete_contact():
"""Delete a contact by name."""
name = input("Enter the name of the contact to delete: ").strip()
if not name:
print("Name is required.")
return
conn = sqlite3.connect('contacts.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM contacts WHERE name=?", (name,))
conn.commit()
conn.close()
if cursor.rowcount > 0:
print("Contact deleted successfully.")
else:
print("Contact not found.")
def main():
"""Main menu loop for the contact management system."""
init_db()
print("Contact Management System")
while True:
print("\n--- Menu ---")
print("1. Add contact")
print("2. View all contacts")
print("3. Search contacts")
print("4. Update contact")
print("5. Delete contact")
print("6. Exit")
choice = input("Choose an option (1-6): ").strip()
if choice == '1':
add_contact()
elif choice == '2':
view_contacts()
elif choice == '3':
search_contact()
elif choice == '4':
update_contact()
elif choice == '5':
delete_contact()
elif choice == '6':
print("Goodbye!")
break
else:
print("Invalid option. Please try again.")
if __name__ == "__main__":
main()
How to Use
Save the code to a file, e.g., contacts_manager.py.
Run it with python contacts_manager.py.
The program creates contacts.db automatically.
Use the menu to manage contacts (name is unique; partial search supported).
Handles errors like duplicate names gracefully.
This is a complete, robust CLI application with CRUD operations.