python-面向对象

1、操作数据库

 1 """
 2 1、连数据库
 3 2、执行sql
 4 3、关闭数据库
 5 """
 6 import pymysql
 7 
 8 
 9 class MysqlDB:
10     # 构造函数:类在实例化自动执行的函数;self,代表本类对象,就是你实例化的那个变量
11     def __init__(self,mysql_info):
12         self.mysql_info = mysql_info
13         self.__connect()
14 
15     # 析构函数:实例被销毁的时候自动执行的函数
16     def __del__(self):
17         self.__close()
18 
19     #定义为私有方法:只能在类里面的函数调用,在类外面不可调用
20     #函数/变量以__开头,就是私有的
21     def __connect(self):
22         self.conn = pymysql.connect(** self.mysql_info)
23         self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
24 
25     def execute(self,sql):
26         self.cursor.execute(sql)
27 
28     def fetchone(self):
29         return self.cursor.fetchone()
30 
31     def fetchall(self):
32         return self.cursor.fetchall()
33 
34     def fetchmany(self,limit):
35         return self.cursor.fetchmany(limit)
36 
37     #定义为私有方法
38     def __close(self):
39         self.cursor.close()
40         self.conn.close()
41 
42 mysql_info = {'host':'xxx',
43               'port':3306,
44               'db':'xxx',
45               'password':'xxx',
46               'charset':'utf8',
47               'autocommit':True,
48               'user':'jxz'
49               }
50 m = MysqlDB(mysql_info)
51 sql1 = 'select * from app_myuser where username="lzh";'
52 sql2 = 'select * from app_myuser;'
53 m.execute(sql1)
54 result1 = m.fetchone()
55 print(result1)
56 # print(result2)
57 
58 # # 在类外面调用私有方法,报错
59 # # AttributeError: 'MysqlDB' object has no attribute 'close'
60 # m.close()
61          

 

posted @ 2020-06-07 22:13  tour8  阅读(156)  评论(0)    收藏  举报