通过面向对象的编程思路封装一个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语句会用到这个方法!