forked from syx9527/LibraryManage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
69 lines (58 loc) · 1.36 KB
/
db.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
import pymysql
import traceback
host = "127.0.0.1"
user = "root"
password = "123456"
database = "ll" # 数据库名字
def get_conn():
"""
链接数据库
:return: 连接,游标
"""
# 创建连接
conn = pymysql.connect(host=host,
user=user,
password=password,
db=database,
)
# 创建游标
cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
return conn, cursor
def close_conn(conn, cursor):
"""
关闭链接
:param conn:
:param cursor:
:return:
"""
if cursor:
cursor.close()
if conn:
conn.close()
def query(sql, *args):
"""
封装通用查询
:param sql:
:param args:
:return: 返回查询到的结果,((),(),)的形式
"""
conn, cursor = get_conn()
cursor.execute(sql, args)
res = cursor.fetchall()
close_conn(conn, cursor)
return res
def exec_(sql):
cursor = None
conn = None
try:
conn, cursor = get_conn()
cursor.execute(sql)
conn.commit() # 提交事务 update delete insert操作
except:
traceback.print_exc()
finally:
close_conn(conn, cursor)
def main():
sql = "select * from student" # mysql查询语句
res = query(sql)
# print(res)