-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepository.py
72 lines (62 loc) · 2.38 KB
/
repository.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
71
72
import pymysql
from config import DB
class Repository:
connection = None
def __init__(self):
self.DB_HOST = DB['HOST']
self.DB_USER = DB['USER']
self.DB_PASSWORD = DB['PASSWORD']
self.DB_NAME = DB['NAME']
self.DB_PORT = DB['PORT']
self.connection = self.__get_connection()
self.auto_commit = True
def execute(self, query, params=None):
return self.__execute_query(query, params)
def __get_connection(self):
open = True
if self.connection is not None:
try:
self.execute("select 1")
open = False
except Exception as e:
open = True
if open:
self.connection = pymysql.connect(host=self.DB_HOST, user=self.DB_USER, passwd=self.DB_PASSWORD, db=self.DB_NAME, port=self.DB_PORT)
return self.connection
def __execute_query(self, query, params=None):
result = list()
try:
with self.connection.cursor() as cursor:
qry_resp = cursor.execute(query, params)
db_rows = cursor.fetchall()
if cursor.description is not None:
field_name = [field[0] for field in cursor.description]
for values in db_rows:
row = dict(zip(field_name, values))
result.append(row)
else:
result.append(qry_resp)
result.append({'last_row_id': cursor.lastrowid})
if self.auto_commit:
self.connection.commit()
except Exception as e:
self.connection.rollback()
print("DB Error in %s, error: %s" % (str(query), repr(e)))
raise e
return result
def bulk_query(self, query, params=None):
try:
with self.connection.cursor() as cursor:
result = cursor.executemany(query, params)
self.connection.commit()
return result
except Exception as err:
self.connection.rollback()
print("DB Error in %s, error: %s" % (str(query), repr(err)))
def begin_transaction(self):
self.connection.begin()
def commit_transaction(self):
self.connection.commit()
self.auto_commit = True
def rollback_transaction(self):
self.connection.rollback()