python连接mysql与方法的封装
2021/5/16 2:55:15
本文主要是介绍python连接mysql与方法的封装,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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() 11 12 # 查询所有数据 13 def fetchall(self, sql): 14 try: 15 self.__execute(sql) 16 return self.cursor.fetchall() 17 except Exception as error: 18 print(error) 19 20 # 查询多条数据 21 def fetchmany(self, sql, size=1): 22 try: 23 self.__execute(sql) 24 return self.cursor.fetchmany(size) 25 except Exception as error: 26 print(error) 27 28 # 查询一条数据 29 def fetchone(self, sql): 30 try: 31 self.__execute(sql) 32 return self.cursor.fetchone() 33 except Exception as error: 34 print(error) 35 36 # 增删改的方法 37 def change(self, sql): 38 try: 39 self.__execute(sql) 40 self.connection.commit() 41 except Exception as error: 42 print(error) 43 44 # 执行的私有方法 45 def __execute(self, sql): 46 self.cursor.execute(sql) 47 48 # 关闭连接和游标 49 def __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) 9 10 # 插入一条语句 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')
这篇关于python连接mysql与方法的封装的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-25MySQL报错Duplicate entry '0' for key 'PRIMARY'
- 2024-05-29阿里 Canal 实时同步 MySQL 增量数据至 ClickHouse 数据库
- 2024-05-24在Linux下管理MySQL的大小写敏感性
- 2024-04-26MySQL查出时间比实际晚8小时的解决方案
- 2024-04-01JPA不识别MySQL的枚举类型
- 2024-03-30mysql数据库表卡死解决方法
- 2024-03-15MySQL多数据源笔记5-ShardingJDBC实战
- 2024-03-11natural join mysql
- 2024-03-11关于VS2017,VS2015 中利用 EF使用Mysql 不显示数据源问题解决方案
- 2024-02-26mysql 阿里云xb后缀备份文件恢复-icode9专业技术文章分享