This repository has been archived by the owner on Jul 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbhelper.py
87 lines (74 loc) · 2.38 KB
/
dbhelper.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import MySQLdb as mysql
import utils
class DBHelper(object):
SETTINGS = None
def __init__(self, table):
self.__table = table
self.__conn = mysql.connect(
DBHelper.SETTINGS['host'],
DBHelper.SETTINGS['username'],
DBHelper.SETTINGS['password'],
DBHelper.SETTINGS['database'],
)
self.__cursor = None
self.__columns = self.__fetch_columns()
@classmethod
def inject_settings(cls, settings):
cls.SETTINGS = settings
def begin_transaction(self):
if self.__cursor:
raise RuntimeError('There is an uncommitted cursor.')
self.__cursor = self.__conn.cursor()
def end_transaction(self):
if self.__cursor:
self.__cursor.close()
self.__cursor = None
def commit(self):
if self.__cursor:
self.__cursor.close()
self.__conn.commit()
self.__cursor = None
else:
utils.warn('Nothing committed!!!')
def select(self, where_clause=None):
self.__check_cursor()
sql = "SELECT * FROM `%s`" % self.__table
if where_clause:
sql += " WHERE %s" % where_clause
utils.debug("Will execute: %s" % sql)
count = self.__cursor.execute(sql)
if count == 0L:
return ()
return self.__cursor.fetchall()
def insert(self, *values):
self.__check_cursor()
cols = ""
for col in self.__columns:
if not cols == "":
cols += ", "
cols += col[0]
vals = ""
for val in values:
if not vals == "":
vals += ", "
if type(val) == type(str()):
vals += "\"%s\"" % val
elif not val:
vals += "NULL"
else:
vals += str(val)
sql = "INSERT INTO `%s` (%s) VALUES (%s)" % (self.__table, cols, vals)
utils.debug("Will execute: %s" % sql)
return self.__cursor.execute(sql)
def close(self):
self.__conn.close()
def __fetch_columns(self):
sql = "DESC `%s`" % self.__table
cursor = self.__conn.cursor()
cursor.execute(sql)
res = cursor.fetchall()
cursor.close()
return res
def __check_cursor(self):
if not self.__cursor:
raise RuntimeError('There is no cursor.')