· last year · Dec 18, 2023, 02:40 PM
1import sqlite3
2
3class ContactManager:
4 def __init__(self, database_name='contacts.db'):
5 self.conn = sqlite3.connect(database_name)
6 self.cursor = self.conn.cursor()
7 self._create_table()
8
9 def _create_table(self):
10 self.cursor.execute('''
11 CREATE TABLE IF NOT EXISTS contacts (
12 id INTEGER PRIMARY KEY AUTOINCREMENT,
13 name TEXT NOT NULL,
14 phone TEXT NOT NULL,
15 email TEXT
16 )
17 ''')
18 self.conn.commit()
19
20 def add_contact(self, name, phone, email):
21 self.cursor.execute('INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)', (name, phone, email))
22 self.conn.commit()
23 print("Контакт додано успішно.")
24
25 def delete_contact(self, contact_id):
26 self.cursor.execute('DELETE FROM contacts WHERE id=?', (contact_id,))
27 self.conn.commit()
28 print("Контакт видалено успішно.")
29
30 def list_contacts(self):
31 self.cursor.execute('SELECT * FROM contacts')
32 contacts = self.cursor.fetchall()
33
34 if not contacts:
35 print("Список контактів порожній.")
36 else:
37 for contact in contacts:
38 print(f"ID: {contact[0]}, Ім'я: {contact[1]}, Телефон: {contact[2]}, Email: {contact[3] or 'Немає'}")
39
40 def close_connection(self):
41 self.conn.close()
42
43# Приклад використання
44contact_manager = ContactManager()
45contact_manager.add_contact("Іван Петров", "123456789", "ivan@example.com")
46contact_manager.add_contact("Марія Сидорова", "987654321", "maria@example.com")
47
48contact_manager.list_contacts()
49contact_manager.delete_contact(1)
50
51contact_manager.list_contacts()
52
53contact_manager.close_connection()
54