-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_storage.py
70 lines (58 loc) · 2.12 KB
/
db_storage.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!usr/bin/python3
"""
Module Name:
db_storage
Module Description:
This module contains one class that manage the database
Module Classes:
- DBStorage
Module Attributes:
- None
"""
import sqlite3
class DBStorage:
"""
The DBStorage class is used to save and load data from a database.
"""
def create_table(self, conn: sqlite3.connect.__class__):
"""
Creates a table in the database with the name "data" and a single column "number".
Args:
conn: Connection object that is used to connect to the database.
"""
conn.execute('''CREATE TABLE IF NOT EXISTS data
(number INTEGER NOT NULL)''')
def connect(self) -> sqlite3.connect.__class__:
"""
Creates a connection to the SQLite database 'database.db'
"""
return sqlite3.connect('database.db')
def save(self, data_dict: dict) -> None:
"""
Saves data from a dictionary to the "data" table in the database.
Args:
dict: A dictionary containing the data to be saved. The keys in the dictionary
are ignored, and only the values are saved.
"""
with self.connect() as conn:
self.create_table(conn)
values = list(data_dict.values())[0]
for value in values:
conn.execute(f"INSERT INTO data (number) VALUES ({value})")
conn.commit()
def reload(self) -> dict:
"""
Retrieves data from the "data" table in the database, deletes
the data from the table and returns the data in a dictionary.
Returns:
A dictionary containing the retrieved data. The keys in the dictionary
are all "data", and the values are a list of integers that represent the
data. If the "data" table is empty, an empty list is returned.
"""
with self.connect() as conn:
self.create_table(conn)
cursor = conn.execute("SELECT number FROM data")
result = [row[0] for row in cursor]
conn.execute("DELETE FROM data")
conn.commit()
return {"data": result}