Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added Practice/esafonova/humans.db
Binary file not shown.
47 changes: 47 additions & 0 deletions Practice/esafonova/task13.1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 1.Написать класс-обертку над SQLite (с возможностями менеджера контекста),
# которая может на вход принимать строки SQL запросов и возвращать данные в формате json.
# Класс должен иметь, как минимум, методы select и execute.
import json
import sqlite3 as sq


class SqLiteWrapper:
def __init__(self, db_name):
with sq.connect(db_name) as self.con:
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Класс с возможностями менеджера контекста" предполагает реализацию в классе методов __enter__ и __exit__. В первом коннект к базе открывается, во втором закрывается.

self.cur = self.con.cursor()

def select(self, req):
self.cur.execute(req)
data = self.cur.fetchall()
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтоб было проще работать с результатом запроса, как со словарем, стоит выполнить такую донастройку коннекшена: conn.row_factory = sqlite3.Row

print(data)
response = []
for i in range(len(data)):
object_map = {}
for j in range(len(data[i])):
key = self.cur.description[j][0]
value = data[i][j]
object_map[key] = value
response.append(object_map)
return json.dumps(response)

def execute(self, req):
self.cur.executescript(req)
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А где commit? Без него изменения не применятся!

if 'CREATE' in req:
return json.dumps({'table': 'created'})
elif 'INSERT' in req:
return json.dumps({'data': 'inserted'})
elif 'DROP' in req:
return json.dumps({'table': 'dropped'})


if __name__ == '__main__':
my_connector = SqLiteWrapper('humans.db')
print(my_connector.execute("""CREATE TABLE IF NOT EXISTS humans (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
)"""))
print(my_connector.execute("INSERT INTO humans VALUES(1,'Mark',33)"))
print(my_connector.execute("INSERT INTO humans VALUES(2,'Petr',29)"))
print(my_connector.select("SELECT * FROM humans"))
print(my_connector.execute("DROP TABLE humans"))