Python连接mysql数据库和关闭数据库的方法

 1 import pymysql
 2 def get_conn():
 3     """
 4     :return: 连接,游标
 5     """
 6     # 创建连接
 7     conn = pymysql.connect(host="hadoop102",
 8                     user="root",
 9                     password="000429",
10                     db="company",
11                     charset="utf8")
12     # 创建游标
13     cursor = conn.cursor()  # 执行完毕返回的结果集默认以元组显示
14     return conn, cursor
15 
16 def close_conn(conn, cursor):
17     if cursor:
18         cursor.close()
19     if conn:
20         conn.close()
21 """
22 ------------------------------------------------------------------------------------
23 """
24 def query(sql,*args):
25     """
26     通用封装查询
27     :param sql:
28     :param args:
29     :return:返回查询结果 ((),())
30     """
31     conn , cursor= get_conn()
32     print(sql)
33     cursor.execute(sql)
34     res = cursor.fetchall()
35     close_conn(conn , cursor)
36     return res
37 """
38 ------------------------------------------------------------------------------------
39 """

 

posted @ 2021-10-06 08:55  靠谱杨  阅读(3006)  评论(0编辑  收藏  举报