让python操作mysql更简单的一个方法

通过面向对象的编程思路封装一个DBUtil类,进而使python通过pymysql包操作mysql更简单!

#coding=utf-8
​
from distutils.command.config import config
from select import select
import pymysql
​
class DBUtil:
    #连接信息
    config = {
        'host':'localhost',
        'port':3306,
        'user':'自己的mysql用户名称',
        'passwd':'自己的mysql密码',
        'db':'sxt',
        'charset':'utf8'
    }
    
    #在构造的时候进行建立连接
    def __init__(self) -> None:
        self.con = pymysql.connect(**DBUtil.config)
        self.cursor = self.con.cursor()
    
    #关闭游标和连接
    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.con:
            self.con.close()
​
    #执行DDL语句
    def execute_ddl(self,sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            print(e)
        finally:
            self.close()
​
    #执行DML语句
    def execute_dml(self,sql,flag,args):
        try:
            #flag=1执行多次次,否则执行一次
            if flag:
                self.cursor.executemany(sql,args)
            else:
                self.cursor.execute(sql,args)
            self.con.commit()
        except Exception as e:
            if self.con:
                self.con.rollback()
        finally:
            self.close()
​
    #执行DQL语句,查一条信息
    def execute_dql_one(self,sql,args):
        try:
            self.cursor.execute(sql,args)
            return self.cursor.fetchone() 
        except Exception as e:
            print(e)
        finally:
            self.close()
​
    #执行DQL语句,查多条信息
    def execute_dql_many(self,sql,num,args):
        try:
            self.cursor.execute(sql,args)
            return self.cursor.fetchmany(num) 
        except Exception as e:
            print(e)
        finally:
            self.close()
​
    def execute_dql_all(self,sql,args):
        try:
            self.cursor.execute(sql,args)
            return self.cursor.fetchall() 
        except Exception as e:
            print(e)
        finally:
            self.close()

函数使用介绍:

注:封装这个类的时候,需要用到的大多数方法都是来自与'游标'cursor中的方法!(极个别不是,注意一下!)

'游标'方法cursor

  • execute(sql)方法

    执行一次sql语句

  • executemany(sql,args)方法

    执行多次sql语句

  • rollback方法

    回滚:修改数据库失败时,让数据库回到修改前的样子

  • fetchone方法

    获取一条信息

  • fetchmany(num)方法

    获取num条信息,如果num大于查找到的信息条数,则获取的是找到的全部信息条数

  • fetchall方法

    获取找到的全部信息

'连接'对象方法con

  • commit方法

    提交执行sql这条事务,主要是DML语句会用到这个方法!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值