-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
50 lines (42 loc) · 1.44 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
#!/usr/bin/python3
import configparser
import pymysql
import warnings
class Database:
def __init__(self):
config = configparser.ConfigParser()
config.read('config.ini')
conn = pymysql.connect(host=config['DATABASE']['HOST'],
port=int(config['DATABASE']['PORT']),
user=config['DATABASE']['USER'],
passwd=config['DATABASE']['PASS'],
db=config['DATABASE']['NAME'],
charset='utf8')
conn.autocommit(False)
# filter duplicate entry warnings
warnings.filterwarnings('ignore', category=pymysql.Warning)
self.conn = conn
self.cur = self.conn.cursor();
# escape special characters for LIKE queries
def escape_like(self, sql):
return self.conn.escape_string(sql).replace('_', '\\_')
# wrap execute to catch SQL errors
def execute(self, sql, args = None):
try:
# store sql and args incase we want to inspect with sql()
self._last_sql = sql
self._last_args = args
self.cur.execute(sql, args)
return self.cur
except pymysql.Error as err:
print(err)
print(self.sql())
exit()
def commit(self):
self.conn.commit()
def close(self):
self.cur.close()
self.conn.close()
# returns the last SQL query called
def sql(self):
return self.cur.mogrify(self._last_sql, self._last_args)