pymysql操作mysql,虽然简单,但每次都要链接数据库,获取cursor,关闭cursor,关闭链接。这些操作无技术含量,还要重复编写!!我们应该想法提高开发效率
下面提供一个简易的DBUtil工具类,帮我们解决代码繁琐问题
import pymysql as pq
class DBUtil:
#连接你的数据库
config = {
"host":"localhost",
"user":"root",
"passwd":'123',
"charset":'utf8',
"db":"your databaseName"
}
def __init__(self):
self.con = pq.connect()
self.cursor = self.con.cursor()
def close(self):
"""
创建connect
创建cursor
"""
if self.con:
self.con.close()
if self.cursor:
self.cursor.close()
def execute_DML(self,sql,*args):
#执行DML语句
try:
self.cursor.execute(sql,args)
self.con.commit()
except Exception as e:
print(e)
finally:
self.close()
def query_one(self,sql,*args):
"""
查询一条语句
"""
try:
self.cursor.execute(sql,args)
return self.cursor.fetchone()
except Exception as e:
print(e)
finally:
self.close()
def query_many(self,sql,*args):
"""
查询多条语句
"""
try:
self.cursor.execute(sql,args)
rs = self.cursor.fetchmany(*args)
except Exception as e:
print(e)
finally:
self.close()
def query_all(self,sql,*args):
"""
查询全部语句
"""
try:
self.cursor.execute(sql,args)
rs = self.cursor.fetchall()
except Exception as e:
print(e)
finally:
self.close()
if __name__ == '__main__':
db = DBUtil()