-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
66 lines (55 loc) · 2.32 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
import sqlite3
class Database:
def __init__(self, dbname="spdata.db", dbtable="general"):
self.dbname = dbname
self.dbtable = dbtable
self.conn = sqlite3.connect(dbname)
self.c = self.conn.cursor()
# Create a table if there is no desired sqlite database table yet
self.c.execute("CREATE TABLE IF NOT EXISTS '%s' (category text, importance integer, futility integer, data text)" % self.dbtable)
# Put the data into database
def input_data(self, category, importance, data):
imp = 0
fut = 0
self.c.execute("SELECT importance, futility FROM '%s' WHERE data = '%s' and category = '%s'" % (self.dbtable, data, category))
result = self.c.fetchone()
if importance > 0:
imp = importance
elif importance < 0:
fut = importance
if result is None:
self.c.execute("INSERT INTO '%s' VALUES('%s', %d, %d, '%s')" % (self.dbtable, category, imp, fut, data))
else:
imp += result[0]
fut += result[1]
self.c.execute("UPDATE '%s' SET 'importance' = %d, 'futility' = %d WHERE data = '%s'" % (self.dbtable, imp, fut, data))
self.commit()
# Return the data we have in the database
def output_data(self):
self.c.execute("SELECT * FROM '%s'" % self.dbtable)
dbdata = self.c.fetchall()
return dbdata
# It is required to commit before ending of program or before closing of connection
def commit(self):
self.conn.commit()
# It is required to save all the changes before disconnecting
def close(self):
self.conn.commit()
self.c.close()
# To prevent object from being removed, we should have this destructor so that we can commit changes and disconnect.
def __del__(self):
self.close()
# It's a self test (just to make sure functions work in an expected way)
if __name__ == '__main__':
db = Database("test.db", "test")
print db.output_data()
db.input_data("general", 1, "haha")
db.input_data("general", 1, "haha")
db = Database("test.db", "test")
print db.output_data()
db.input_data("general", -1, "haha")
db.input_data("general", -1, "haha")
db.input_data("general", -1, "haha")
db.input_data("general", -1, "hohoho")
print db.output_data()
db.close()