1
import
pymysql
2
3
class
Model(object):
4
def
__init__(self, username=‘root‘, password=‘123456‘, database=‘demo‘,
5 port=3306, host=‘localhost‘):
6# 创建连接 7 self.connection = pymysql.connect(user=username, password=password, database=database,
8 port=port, host=host, cursorclass=pymysql.cursors.DictCursor)
9# 创建游标10 self.cursor = self.connection.cursor()
1112# 查询所有数据13def fetchall(self, sql):
14try:
15 self.__execute(sql)
16return self.cursor.fetchall()
17except Exception as error:
18print(error)
1920# 查询多条数据21def fetchmany(self, sql, size=1):
22try:
23 self.__execute(sql)
24return self.cursor.fetchmany(size)
25except Exception as error:
26print(error)
2728# 查询一条数据29def fetchone(self, sql):
30try:
31 self.__execute(sql)
32return self.cursor.fetchone()
33except Exception as error:
34print(error)
3536# 增删改的方法37def change(self, sql):
38try:
39 self.__execute(sql)
40 self.connection.commit()
41except Exception as error:
42print(error)
4344# 执行的私有方法45def__execute(self, sql):
46 self.cursor.execute(sql)
4748# 关闭连接和游标49def__del__(self):
50 self.connection.close()
51 self.cursor.close()
1
from data_connect import model
2 3# 实例化Model类 4 employee = model.Model()
5 res = employee.fetchall(‘select nickname from employee where job="头领"‘)[0]
6 res1 = employee.fetchmany(‘select nickname from employee where job="头领"‘, 2)
7 res2 = employee.fetchone(‘select nickname from employee where name = "宋江"‘)
8# print(res2) 910# 插入一条语句11 employee.change(‘insert into employee (name)values ("关羽")‘)
12# 删除一条语句13 employee.change(‘delete from employee where name="关羽"‘)
14# 更新一条语句15# obj.change(‘update employee set name="张飞"where id=8004‘)
原文:https://www.cnblogs.com/Liu928011/p/14773058.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!