-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_connector.py
33 lines (31 loc) · 1.27 KB
/
db_connector.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
import mysql.connector
import logging as logger
class Database:
connection = None
def __init__(self):
if self.connection is None or self.connection.is_connected() == False:
self.connection = mysql.connector.connect(
user="root",
password="",
host="localhost",
database="ta_vegetables",
)
self.connection.autocommit = False
def query(self, query, autoCommit=None, fetch="ALL"):
try:
cursor = self.connection.cursor()
result = cursor.execute(query)
if autoCommit is not None:
self.connection.commit()
operation = True if cursor.lastrowid == 0 else {"id": cursor.lastrowid}
return {"data": operation}
fields = [field_md[0] for field_md in cursor.description]
if fetch != "SINGLE":
result = [dict(zip(fields, row)) for row in cursor.fetchall()]
return {"data": result}
else:
result = [dict(zip(fields, row)) for row in cursor.fetchone()]
return {"data": result}
except Exception as e:
logger.error(e)
return {"data": None, "error": e, "query": query}