工作需要使用mysql数据库,肯定要用到sql语句啊,创建语句的过程大家应该知道,简单再提一下:
# 导入 pymysql 模块
import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='128556', db='tmpdb')
# 获取光标
cursor = conn.cursor()
# 执行增删改查
# 插入语句
result = cursor.execute("insert into tmp(name) values (%s)", ("jim"))
# 修改后提交
conn.commit()
# 查询语句
cursor.execute('select * from tmp')
r = cursor.fetchone()
print(r)
# 获取所有的值
values = cursor.fetchall()
print(values)
# 删除语句 修改语句 与上面差不多
# 关闭光标
cursor.close()
# 关闭连接
conn.close()
一个项目的语句千变万化,繁琐复杂,不可能一个个的语句都用上面的过程执行,费事。
所以就需要封装一个类,来帮我们办这个事,类的好处我上一篇文章简单说了下,有兴趣可以去看看。
封装过程如下:
conn_mysql.py
import pymysql
# 单例模式 保证全局环境下只能有一个该类的实例 避免多次实例对象造成浪费
def singleton(cls):
__instance = {}
def wrapper(*args, **kwargs):
if cls not in __instance:
__instance[cls] = cls(*args, **kwargs)
return __instance[cls]
else:
return __instance[cls]
return wrapper
@singleton
class MySQLTool:
def __init__(self, host, user, password, database):
self.connection = pymysql.connect(host=host,
user=user,
password=password,
database=database)
self.cursor = self.connection.cursor(pymysql.cursors.DictCursor)
def query(self, sql, params=None):
self.cursor.execute(sql, params or ())
return self.cursor.fetchall()
def insert(self, sql, params=None):
self.cursor.execute(sql, params or ())
self.connection.commit()
return self.cursor.lastrowid
def update(self, sql, params=None):
self.cursor.execute(sql, params or ())
self.connection.commit()
return self.cursor.rowcount
def delete(self, sql, params=None):
self.cursor.execute(sql, params or ())
self.connection.commit()
return self.cursor.rowcount
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.cursor.close()
self.connection.close()
print("已关闭数据库")
if __name__ == '__main__':
# with as 作用就是 执行完内容后会自动调用 __exit__方法,你就不用每次手动关闭了
with MySQLTool('localhost', 'root', 'root', 'silicon_traceability_1') as db_tool:
# 这里执行数据库操作
result = db_tool.query("SELECT * FROM contracts")
print(result)
print(id(db_tool))
好了,这样你需要使用数据库的话,只需要在其他地方导入,就可以使用了
import conn_mysql
# 创建实例
db_tool = conn_mysql.MySQLTool('localhost', 'root', '123456', 'datebase1')
# 执行语句
result = db_tool.query("SELECT * FROM `table_1`", ())
是不是超简单!
工作过程中,会遇到执行很多很多sql的情况,不可避免的会有重复创建实例化对象的问题,造成内存空间浪费问题。
上面的封装中,我添加了单例模式避免这个问题。
# 单例模式 保证全局环境下只能有一个该类的实例 避免多次实例对象造成浪费
def singleton(cls):
__instance = {}
def wrapper(*args, **kwargs):
if cls not in __instance:
__instance[cls] = cls(*args, **kwargs)
return __instance[cls]
else:
return __instance[cls]
return wrapper
有想了解的我可以后面说一下单例模式,你只需要记住单例模式,它就是让你创建了对象以后,再次创建这个对象还是它,不会造成多次创建浪费内存。
使用方法也很简单,上面的代码放在一个地方,在需要使用单例模式的类上加一个装饰器,就比如上面封装的MysqlTool类:
# 单例模式 保证全局环境下只能有一个该类的实例 避免多次实例对象造成浪费
def singleton(cls):
__instance = {}
def wrapper(*args, **kwargs):
if cls not in __instance:
__instance[cls] = cls(*args, **kwargs)
return __instance[cls]
else:
return __instance[cls]
return wrapper
@singleton
class MySQLTool:
好啦,你就算执行再多语句,也不怕啦。