【pymysql】基于pymysql封装的MySQL增删改查操作
1. 官网
https://pymysql.readthedocs.io/en/latest/
2. 安装
You can install it with pip: $ python3 -m pip install PyMySQL To use "sha256_password" or "caching_sha2_password" for authenticate, you need to install additional dependency: $ python3 -m pip install PyMySQL[rsa] To use MariaDB's "ed25519" authentication method, you need to install additional dependency: $ python3 -m pip install PyMySQL[ed25519]
3. 官方示例
import pymysql.cursors # Connect to the database connection = pymysql.connect(host='localhost', user='user', password='passwd', database='db', cursorclass=pymysql.cursors.DictCursor) with connection: with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('webmaster@python.org', 'very-secret')) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('webmaster@python.org',)) result = cursor.fetchone() print(result)
4. 关于cursor
1. 最常用的也是默认的游标就是cursor,返回的数据格式为tuple
2. 其余的游标类型还有DictCursor,SSCursor,SSDictCursor等,SS开头的游标称为流式游标,
3. Cursor和DictCursor游标可以一次性返回所有的数据,
4. 流式游标智能一条一条得返回查询数据,所以这类游标适用于内存低、网络带宽小、数据量大的应用场景中。
DictCursor:返回字典(Dict)格式的数据
SSCursor:流式游标返回元组(Tuple)格式数据
SSDictCursor:流式游标返回字典(Dict)格式数据
5. github
https://github.com/PyMySQL/PyMySQL
6. 封装
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql from pymysql import cursors from common.framework.utils import debug_logger from conf import config class MysqlConnectCom(object): def __init__(self, db, user, passwd, host='localhost', port=3306, charset='utf8'): self.db = db self.user = user self.passwd = passwd self.host = host self.port = port self.charset = charset self.connect = None self.cursor = None def _connect_db(self): params = { "db": self.db, "user": self.user, "passwd": self.passwd, "host": self.host, "port": self.port, "charset": self.charset } self.connect = pymysql.connect(**params) self.cursor = self.connect.cursor(cursors.DictCursor) def _close_db(self): """ 关闭数据库 """ self.cursor.close() self.connect.close() def select_operation(self, sql): if not sql.upper().startswith('SELECT'): debug_logger.error(f'[mysql] sql not startswith SELECT') return Exception('sql not right!') try: self.cursor.execute(sql) except Exception as e: debug_logger.error(f'[mysql]{e}') return [] else: return self.cursor.fetchall() finally: self._connect_db() def insert_operation(self, sql): if not sql.upper().startswith('INSERT'): debug_logger.error(f'[mysql] sql not startswith INSERT') return Exception('sql not right!') try: count = self.cursor.execute(sql) self.connect.commit() except Exception as e: debug_logger.error(f'[mysql]{e}') self.connect.rollback() return False else: return count finally: self._connect_db() def update_operation(self, sql): if not sql.upper().startswith('UPDATE'): debug_logger.error(f'[mysql] sql not startswith UPDATE') return Exception('sql not right!') try: count = self.cursor.execute(sql) self.connect.commit() except Exception as e: debug_logger.error(f'[mysql]{e}') self.connect.rollback() return False else: return count finally: self._connect_db() def delete_operation(self, sql): if not sql.upper().startswith('DELETE'): debug_logger.error(f'[mysql] sql not startswith DELETE') return Exception('sql not right!') try: count = self.cursor.execute(sql) self.connect.commit() except Exception as e: debug_logger.error(f'[mysql]{e}') self.connect.rollback() return False else: return count finally: self._connect_db() if __name__ == "__main__": client = MysqlConnectCom(config.DATABASE , config.USER, config.PASSWORD, host=config.HOST) client._connect_db() # print(client.select_operation("SELECT * FROM student;"))
参考链接:
https://blog.csdn.net/qq_39241986/article/details/109882056
https://www.cnblogs.com/du-hong/p/10897822.html
https://www.cnblogs.com/zc110/p/12850428.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2019-03-16 单例模式的python实现
2019-03-16 工厂模式的python实现