-
Notifications
You must be signed in to change notification settings - Fork 5
/
db.py
104 lines (66 loc) · 2.39 KB
/
db.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
88
89
90
91
92
93
94
95
96
97
98
99
100
import MySQLdb
import sqlite3
class Db:
def __init__(self, credentials):
self.credentials = credentials
self.conn = MySQLdb.connect(**credentials)
def query(self, sql, params = None):
curs = self.curs()
if params is None:
curs.execute(sql)
else:
curs.execute(sql, params)
return curs.fetchall()
def curs(self):
return self.conn.cursor()
def query_dict(self, sql, params = None):
curs = self.conn.cursor(MySQLdb.cursors.DictCursor)
if params is None:
curs.execute(sql)
else:
curs.execute(sql, params)
return curs.fetchall()
def getCredentials(self):
credentials = self.credentials.copy()
del credentials['passwd']
return credentials
def insert_or_update(self, table_name, data):
curs = self.curs()
lastrowid = None
for line in data:
headers = [key for key,val in sorted(line.items())]
quoted_values = ['"%s"' % (val.replace('"','\\"') if type(val) is str else val) for key,val in sorted(line.items())]
duplicate_key_clauses = ['%s="%s"' % (key, val.replace('"','\\"') if type(val) is str else val) for key,val in sorted(line.items())]
sql = """
INSERT INTO %s
(%s)
VALUES (%s)
ON DUPLICATE KEY UPDATE
%s
""" % (table_name, ','.join(headers), ','.join(quoted_values),','.join(duplicate_key_clauses))
curs.execute(sql)
lastrowid = curs.lastrowid
self.conn.commit()
if len(data) == 1:
return lastrowid
else:
return None
class DbLite:
def __init__(self):
self.conn = sqlite3.connect("metadata/leagues.db")
self.conn.row_factory = sqlite3.Row
def query(self, sql):
curs = self.curs()
curs.execute(sql)
return curs.fetchall()
def curs(self):
return self.conn.cursor()
def query_dict(self, sql, params = None):
curs = self.conn.cursor()
if params is None:
curs.execute(sql)
else:
curs.execute(sql, params)
return [dict(zip(row.keys(), row)) for row in curs.fetchall()]
def commit(self):
self.conn.commit()