栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【专题】python封装MySQL类

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【专题】python封装MySQL类

文章目录
Python创建连接MySQL类 实例方法 连接 查询 执行sql

import mysql

class DBUtil():
	def __init__(self) -> None:
        """
        初始化数据
        """
        # 连接数据库信息
        self._host = ''
        self._user = ''
        self._pwd = '-'
        self._name = ''
        self._port = 
        self._charset = 'utf8'
        self._conn = self.connect_mysql()

        if self._conn:
            self._cursor = self._conn.cursor(cursor=pymysql.cursors.DictCursor)
            
	def connect_mysql(self):
        """
        建立数据库连接
        """
        try:
            conn = pymysql.connect(host=self._host,
                                   user=self._user,
                                   passwd=self._pwd,
                                   db=self._name,
                                   port=self._port,
                                   cursorclass=pymysql.cursors.DictCursor,
                                   charset=self._charset)
        except Exception as e:
            raise("数据库连接异常")
        return conn

    def close(self):
        """
        关闭数据库连接
        """
        if self._conn:
            try:
                if (type(self._cursor) == 'object'):
                    self._conn.close()
                if (type(self._conn) == 'object'):
                    self._conn.close()
            except Exception:
                raise("关闭数据库连接异常")

    def execute_sql(self,sql,*args):
        """
        执行sql
        """
        res = ''
        try:
            self._conn.begin()
            data = self._cursor.execute(sql,args)
            self._conn.commit()
        except Exception:
            self._conn.rollback()
            raise("执行sql异常")
        self.close()
        return data
    
    def select(self, sql, *args):
        """
        查询sql
        """
        try:
            self._conn.begin()
            self._cursor.execute(sql, *args)
            data = self._cursor.fetchall()
            if not data:
                date = False
        except Exception as e:
            self._conn.rollback()
            raise("查询异常")
        self.close()
        return data

    def exists(self,sql):
        """
        判断是否存在
        """
        flag = False
        try:
            self._conn.begin()
            self._cursor.execute(sql)
            data =self._cursor.fetchall()
            if data:
                flag = True
        except Exception as e:
            self.conn.rollback()
            raise("执行异常")
        self.close()
        return flag


if __name__ == '__main__':
    db = DBUtil()
    sql = "select * from test where id = %s" % 1
    print(db.execute_sql(sql))
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1010300.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号