-
Notifications
You must be signed in to change notification settings - Fork 5
/
database.py
73 lines (66 loc) · 1.56 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
import threading
import _mysql
from settings import Settings
database_lock = threading.Lock()
try:
# Although SQLAlchemy is optional, it is highly recommended
import sqlalchemy.pool as pool
_mysql = pool.manage( module = _mysql,
pool_size = Settings.DATABASE_POOL_SIZE,
max_overflow = Settings.DATABASE_POOL_OVERFLOW)
Settings._.USING_SQLALCHEMY = True
except ImportError:
pass
def ConnectDb():
"""
Get a connection to the database
"""
return _mysql.connect(host = Settings.DATABASE_HOST,
user = Settings.DATABASE_USERNAME,
passwd = Settings.DATABASE_PASSWORD,
db = Settings.DATABASE_DB)
def FetchAll(query, method=1):
"""
Query and fetch all results as a list
"""
db = ConnectDb()
try:
db.query(query)
r = db.use_result()
return r.fetch_row(0, method)
finally:
db.close()
def FetchOne(query, method=1):
"""
Query and fetch only the first result
"""
db = ConnectDb()
try:
db.query(query)
r = db.use_result()
try:
return r.fetch_row(1, method)[0]
except:
return None
finally:
db.close()
def UpdateDb(query):
"""
Update the DB (UPDATE/DELETE) and return # of affected rows
"""
db = ConnectDb()
try:
db.query(query)
return db.affected_rows()
finally:
db.close()
def InsertDb(query):
"""
Insert into the DB and return the primary key of new row
"""
db = ConnectDb()
try:
db.query(query)
return db.insert_id()
finally:
db.close()