大虾

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

    

        
posted on 2022-11-29 20:57  一灯编程  阅读(215)  评论(0编辑  收藏  举报