1 import pymysql
 2 from day8.homework.const import mysql_info
 3 class MySQL: #经典类
 4 
 5     def __init__(self,mysql_info,data_type=1):
 6         self.mysql_info = mysql_info
 7         self.data_type = data_type
 8         self.__connect_status = False
 9         self.__connect()
10 
11     def __connect(self):
12         print("开始连接mysql")
13         try:
14             self.__conn = pymysql.connect(**self.mysql_info)
15         except:
16             print("数据库连接出错!" )
17             raise Exception("数据库连接出错")
18         self.__connect_status = True
19         if self.data_type != 1:
20             self.__cur = self.__conn.cursor(pymysql.cursors.DictCursor)
21         else:
22             self.__cur = self.__conn.cursor()
23         print("mysql连接成功!")
24 
25     def execute(self,sql):
26         print("开始执行sql",sql)
27         try:
28             self.__cur.execute(sql)
29         except:
30             print("sql不正确,sql语句是%s" % sql)
31         else:
32             print("sql执行完成!")
33             return True
34 
35     def fetchone(self,sql):
36         if self.execute(sql):
37             return self.__cur.fetchone()
38 
39     def fetchall(self,sql):
40         if self.execute(sql):
41             return self.__cur.fetchall()
42 
43     def __del__(self):
44         self.__close()
45         print("mysql 连接关闭完成")
46 
47     def __close(self):
48         if self.__connect_status:
49             self.__cur.close()
50             self.__conn.close()