-
Notifications
You must be signed in to change notification settings - Fork 1
/
database_utils.py
70 lines (58 loc) · 2.29 KB
/
database_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
68
69
70
import pymysql.cursors
def mysql_query(connection, web):
# 数据库链接信息
db = pymysql.connect(host=connection['host'],
port=connection['port'],
user=connection['user'],
password=connection['password'],
database=connection['database'])
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句,查询user表
sql = 'SELECT title, detail, publish_time from posts where web = \'{}\' order by publish_time desc, post_id desc'.format(web)
# 执行sql语句查询
cursor.execute(sql)
# 这是获取表中第一个数据
rest = cursor.fetchone()
db.close()
return rest
# 关闭数据库连接
def get_receivers(connection):
# 数据库链接信息
db = pymysql.connect(host=connection['host'],
port=connection['port'],
user=connection['user'],
password=connection['password'],
database=connection['database'])
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句,查询user表
sql = 'SELECT name, email from receivers where subscription = 1'
# 执行sql语句查询
cursor.execute(sql)
# 这是获取表中全部数据
rest = cursor.fetchall()
db.close()
return rest
# 关闭数据库连接
def mysql_insert(connection: dict, post: list, web):
# 数据库链接信息
db = pymysql.connect(host=connection['host'],
port=connection['port'],
user=connection['user'],
password=connection['password'],
database=connection['database'])
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句,查询user表
sql = 'insert into posts(publish_time, web, title, detail, content) values (\'{}\',\'{}\',\'{}\',\'{}\',\'{}\')'\
.format(post[2],web, post[0], post[1], "content")
# 执行sql语句查询
cursor.execute(sql)
# 这是获取表中第一个数据
db.commit()
# 关闭数据库连接
cursor.close()
db.close()
if __name__ == "__main__":
pass