封装一个python的pymysql操作类

作者:野生大虾 时间:2024-01-19 09:44:47 

最近使用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()

来源:https://www.cnblogs.com/mooremok/p/16936688.html

标签:pymysql操作类
0
投稿

猜你喜欢

  • Django REST Framework之频率限制的使用

    2021-01-25 17:59:42
  • python检测服务器端口代码实例

    2023-07-07 06:34:14
  • 简化SQL Server备份与还原到云工作原理及操作方法

    2024-01-18 14:27:36
  • 详解Vue 事件驱动和依赖追踪

    2024-04-10 10:32:10
  • Python常用数据分析模块原理解析

    2023-07-12 03:46:31
  • MySQL数据库远程访问权限设置方式

    2024-01-22 06:58:43
  • Python3+PyCharm+Django+Django REST framework配置与简单开发教程

    2023-06-15 09:26:28
  • 浅谈python中scipy.misc.logsumexp函数的运用场景

    2023-11-10 17:10:56
  • position:relative/absolute无法冲破的等级

    2007-05-11 17:03:00
  • Yii2基于Ajax自动获取表单数据的方法

    2023-11-21 00:59:56
  • BootstrapValidator超详细教程(推荐)

    2024-04-10 13:53:24
  • MySQL 一次执行多条语句的实现及常见问题

    2024-01-12 20:03:23
  • PHP简易延时队列的实现流程详解

    2023-05-29 23:02:48
  • 利用FrontPage 2003制作网络申请系统

    2008-02-21 14:34:00
  • 浅谈python for循环的巧妙运用(迭代、列表生成式)

    2023-04-15 02:17:29
  • python实现将JPG、BMP图片转化为bgr

    2023-09-16 05:01:06
  • js匿名函数作为函数参数详解

    2024-04-16 09:23:52
  • keras中epoch,batch,loss,val_loss用法说明

    2021-08-11 10:56:30
  • MySQL中导出用户权限设置的脚本分享

    2024-01-21 15:29:04
  • ASP保存远程图片到本地 同时取得第一张图片并创建缩略图的代码

    2011-04-19 11:07:00
  • asp之家 网络编程 m.aspxhome.com