-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
111 lines (87 loc) · 3.1 KB
/
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
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
101
102
103
104
105
106
107
108
109
110
111
import mysql.connector
def opendb(name):
if name == "questiongame" or name == "main":
return Database("questiongame")
return None
class Database:
def __init__(self, name):
self.db = mysql.connector.connect(
host='localhost',
user='python',
passwd='!nnov4tion',
database=name
)
self.cursorObject = self.db.cursor()
self.open = True
def close(self):
self.db.close()
self.open = False
def select(self, tablename, rownames, condition="true"):
if not self.open:
raise Exception("Database is not open!")
rowstr = ""
if type(rownames) is str:
rowstr = rownames
else:
for row in rownames:
rowstr += row
rowstr += ", "
rowstr = rowstr[:-2]
self.cursorObject.execute("SELECT " + rowstr + " FROM " + tablename + " WHERE " + condition)
return self.cursorObject.fetchall()
def insert(self, tablename, vals, varnames=None):
if not self.open:
raise Exception("Database is not open!")
valsstr = ""
if type(vals) is str:
valsstr = vals
else:
for val in vals:
if type(val) is str:
valsstr += "\"" + val + "\""
else:
valsstr += val
valsstr += ", "
valsstr = "(" + valsstr[:-2] + ")"
varstr = ""
if varnames is not None:
if type(varnames) is str:
varstr = "(" + varnames + ")"
else:
for val in varnames:
varstr += val
varstr += ", "
varstr = "(" + varstr[:-2] + ")"
query = "INSERT INTO " + tablename + " " + varstr + " VALUES " + valsstr
self.cursorObject.execute(query)
self.db.commit()
def rawCommand(self, command):
self.cursorObject.execute(command)
self.db.commit()
return self.cursorObject.fetchall()
def update(self, tablename, setting, condition):
if not self.open:
raise Exception("Database is not open!")
settingstr = ""
if type(setting) is str:
settingstr = setting
elif type(setting) is tuple:
temp = setting[1]
if type(temp) is str:
temp = "\"" + temp + "\""
settingstr = setting[0] + "=" + temp
else:
for val in setting:
temp = val[1]
if type(temp) is str:
temp = "(" + temp + ")"
settingstr += val[0] + "=" + temp + ", "
settingstr = settingstr[:-2]
query = "UPDATE " + tablename + " SET " + settingstr + " WHERE " + condition
self.cursorObject.execute(query)
self.db.commit()
def delete(self, tablename, condition):
if not self.open:
raise Exception("Database is not open!")
self.cursorObject.execute("DELETE FROM " + tablename + " WHERE " + condition)
self.db.commit()