python操作mysql工具类

某次爬虫写的一个简单的python连接MySQL的工具类

import pymysql

class MysqlTool:
    # 初始化连接参数,不传的话使用默认
    def __init__(self, host='127.0.0.1', user='root', passwd='root', db='test', charset='utf8'):
        self.host = host
        self.uNmae = user
        self.pwd = passwd
        self.db = db
        self.charset = charset
	# 建立连接
    def connection(self):
        try:
            conn = pymysql.connect(host=self.host, user=self.uNmae, passwd=self.pwd, db=self.db, charset=self.charset)
            return conn
        except pymysql.Error as e:
            print(f"连接时发生错误: {e}")
            raise
	# 以下为增删改查
    def insert(self, cur, sql, args):
        try:
            cur.execute(sql, args)
        except pymysql.Error as e:
            print(f"插入时发生错误: {e}")
            raise

    def insert_many(self, cur, sql, args):
        try:
            cur.executemany(sql, args)
        except pymysql.Error as e:
            print(f"插入多行时发生错误: {e}")
            raise

    def select_all(self, cur, sql):
        try:
            cur.execute(sql)
            data = cur.fetchall()
            return data
        except pymysql.Error as e:
            print(f"查询时发生错误: {e}")
            raise

    def update(self, cur, sql, args=None):
        try:
            if args:
                cur.execute(sql, args)
            else:
                cur.execute(sql)
        except pymysql.Error as e:
            print(f"更新时发生错误: {e}")
            raise
	# 关闭连接
    def close_all(self, conn, cur):
        try:
            cur.close()
            conn.close()
        except pymysql.Error as e:
            print(f"关闭连接时发生错误: {e}")
            raise

谢谢你请我吃糖,我会更加努力的! ヾ(^▽^*)))
小白菜T_T - 支付宝 支付宝
小白菜T_T - 微信 微信