封装一个python的pymysql操作类
作者:野生大虾
这篇文章主要介绍了封装一个python的pymysql操作类的相关资料,需要的朋友可以参考下
最近使用pymysql写脚本的情况越来越多了,刚好整理,简单封装一个pymysql的操作类
import pymysql class MysqlDB: def __init__( self, host=None, port=None, db=None, account=None, password=None, connect_timeout=20, read_timeout=20, write_timeout=20 ): self.conn = pymysql.connect( host=self.host, port=self.port, db=self.db, user=self.account, passwd=self.password, connect_timeout=self.connect_timeout, read_timeout=self.read_timeout, write_timeout=self.write_timeout ) def fetch(self, table_name=None, fields=(), where=None, many=False): cur = self.conn.cursor() if where: sql = f'select {",".join(fields)} from {table_name} where {where}' else: sql = f'select {",".join(fields)} from {table_name}' cur.execute(sql) if many: data = cur.fetchmany() else: data = cur.fetchone() cur.close() return data def update(self, table_name=None, field=None, value=None, where=None): cur = self.conn.cursor() sql = f'update {table_name} set {field} = {value}' if where: sql += f'where {where}' cur.execute(sql) self.conn.commit() cur.close() def insert(self, table_name=None, single=True, data_list: list = []): cur = self.conn.cursor() for data in data_list: sql = f'insert into {table_name}({",".join([key for key in data.keys()])}) values({",".join(["%s" for _ in range(len(data.keys()))])})' cur.execute(sql, data) self.conn.commit() cur.close() def quit(self): self.conn.close()
到此这篇关于封装一个python的pymysql操作类的文章就介绍到这了,更多相关封装pymysql操作类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
- Python中操作mysql的pymysql模块详解
- Python中模块pymysql查询结果后如何获取字段列表
- Python MySQL数据库连接池组件pymysqlpool详解
- 在python中使用pymysql往mysql数据库中插入(insert)数据实例
- pymysql之cur.fetchall() 和cur.fetchone()用法详解
- Python使用pymysql从MySQL数据库中读出数据的方法
- python使用pymysql实现操作mysql
- pyMySQL SQL语句传参问题,单个参数或多个参数说明
- 详解使用pymysql在python中对mysql的增删改查操作(综合)
- Python中pymysql 模块的使用详解