-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
34 lines (28 loc) · 880 Bytes
/
database.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
import inject
import mysql.connector
from config import Config
from contextlib import contextmanager
class Database:
config = inject.attr(Config)
@contextmanager
def connect(self):
connector = mysql.connector.connect(**self.config.mysql.__dict__)
try:
yield connector
finally:
connector.close()
@contextmanager
def cursor(self, commit_changes=False):
with self.connect() as connector:
cursor = connector.cursor()
try:
yield cursor
if commit_changes:
connector.commit()
finally:
cursor.close()
@contextmanager
def execute(self, query: str, *args, commit_changes=False):
with self.cursor(commit_changes) as cursor:
cursor.execute(query, args)
yield cursor