-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysql_utils.py
67 lines (60 loc) · 1.76 KB
/
mysql_utils.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
import pymysql
import datetime
# mySQL
MYSQL_HOST = 'localhost'
MYSQL_UN = 'root'
MYSQL_PW = 'test_root'
MYSQL_DB = 'academicworld'
# MySQL Config
try:
db = pymysql.connect(host=MYSQL_HOST,
user=MYSQL_UN,
password=MYSQL_PW,
database=MYSQL_DB,
charset='utf8mb4',
port=3306,
cursorclass=pymysql.cursors.DictCursor)
except:
print("Error with MySQL connect ")
db = None
UPDATE_KEYWORD = """UPDATE keyword
SET rating = {rating}, rating_date = '{rating_date}'
WHERE name = '{keyword}';"""
GET_RECENT = """SELECT name, rating
FROM keyword
WHERE rating_date IS NOT NULL
ORDER BY rating_date DESC
LIMIT 10
"""
def execute_write(query):
if db == None:
return
try:
with db.cursor() as cursor:
cursor.execute('USE academicworld;')
cursor.execute(query)
db.commit()
except pymysql.Error as e:
print("Error with MySQ write: {}".format(e))
return None
def execute_read(query):
if db == None:
return
try:
with db.cursor() as cursor:
cursor.execute('USE academicworld;')
cursor.execute(query)
result = cursor.fetchall()
return result
except:
print("Error with MySQL read")
return None
# add keyword rating and rating time to db
def rate_keyword(keyword, rating):
now = datetime.datetime.utcnow()
now_format = now.strftime('%Y-%m-%d %H:%M:%S')
query = UPDATE_KEYWORD.format(rating=rating, rating_date=now_format, keyword=keyword)
execute_write(query)
# add keyword rating and rating time to db
def get_recently_rated():
return execute_read(GET_RECENT)