forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
52 lines (42 loc) · 1.33 KB
/
Copy pathdatabase.py
File metadata and controls
52 lines (42 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import pathlib
import sqlite3
DATABASE_PATH = pathlib.Path().home() / "contacts.db"
class Database:
def __init__(self, db_path=DATABASE_PATH):
self.db = sqlite3.connect(db_path)
self.cursor = self.db.cursor()
self._create_table()
def _create_table(self):
query = """
CREATE TABLE IF NOT EXISTS contacts(
id INTEGER PRIMARY KEY,
name TEXT,
phone TEXT,
email TEXT
);
"""
self._run_query(query)
def _run_query(self, query, *query_args):
result = self.cursor.execute(query, [*query_args])
self.db.commit()
return result
def get_all_contacts(self):
result = self._run_query("SELECT * FROM contacts;")
return result.fetchall()
def get_last_contact(self):
result = self._run_query(
"SELECT * FROM contacts ORDER BY id DESC LIMIT 1;"
)
return result.fetchone()
def add_contact(self, contact):
self._run_query(
"INSERT INTO contacts VALUES (NULL, ?, ?, ?);",
*contact,
)
def delete_contact(self, id):
self._run_query(
"DELETE FROM contacts WHERE id=(?);",
id,
)
def clear_all_contacts(self):
self._run_query("DELETE FROM contacts;")