-
Notifications
You must be signed in to change notification settings - Fork 0
Esafonova #94
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Esafonova #94
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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: | ||
| self.cur = self.con.cursor() | ||
|
|
||
| def select(self, req): | ||
| self.cur.execute(req) | ||
| data = self.cur.fetchall() | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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")) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
"Класс с возможностями менеджера контекста" предполагает реализацию в классе методов
__enter__и__exit__. В первом коннект к базе открывается, во втором закрывается.