-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
91 lines (75 loc) · 2.87 KB
/
db.py
File metadata and controls
91 lines (75 loc) · 2.87 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import os.path
import sqlite3
class DataBase:
db = 'db.db'
sql = 'sql.sql'
def __init__(self, create_table=False):
if not os.path.exists(self.db):
create_table = True
self.__db = sqlite3.connect(self.db)
self.__db.row_factory = sqlite3.Row
self.__cur = self.__db.cursor()
if create_table:
self.create_table()
def create_table(self):
with open(self.sql, 'r') as data_base:
self.__cur.executescript(data_base.read())
self.__db.commit()
def add_item(self, table, column, value):
try:
self.__cur.execute(f'INSERT INTO {table} ("{column}") VALUES ("{value}");')
except sqlite3.Error as e:
print('Ошибка записи в БД:', e)
def add_items(self, table, columns, values):
try:
self.__cur.execute(f'INSERT INTO {table} {columns} VALUES {values};')
except sqlite3.Error as e:
print('Ошибка записи в БД:', e)
def update_item(self, table, item_id, column, value):
try:
self.__cur.execute(f'UPDATE {table} SET {column}={value} WHERE id={item_id};')
self.__db.commit()
except sqlite3.Error as e:
print('Ошибка обновления данных в БД:', e)
def get_item(self, table, item_id):
try:
self.__cur.execute(f'SELECT * FROM {table} WHERE id={item_id};')
return self.__cur.fetchone()
except sqlite3.Error as e:
print('Ошибка чтения БД:', e)
return None
def get_item_count(self, table, column, value):
try:
self.__cur.execute(f'SELECT count(id) FROM {table} WHERE {column}={value};')
return self.__cur.fetchone()[0]
except sqlite3.Error as e:
print('Ошибка чтения БД:', e)
return None
def get_all_items(self, table):
try:
self.__cur.execute(f'SELECT * FROM {table};')
return self.__cur.fetchall()
except sqlite3.Error as e:
print('Ошибка чтения БД:', e)
return None
def clear_table(self, table):
try:
self.__cur.execute(f'DELETE FROM {table};')
self.__cur.execute(f'DELETE FROM sqlite_sequence where name="{table}";')
self.__db.commit()
except sqlite3.Error as e:
print('Ошибка удаления из БД:', e)
def commit(self):
try:
self.__db.commit()
except sqlite3.Error as e:
print('Ошибка commit в БД:', e)
def __del__(self):
self.__db.commit()
self.__db.close()
if __name__ == '__main__':
db = DataBase()
db.clear_table('item_names')
db.clear_table('markets')
db.clear_table('categories')
db.clear_table('subcategories')