pymysql装饰器封装

def openClose(fun):
def run(sql=None):
coon =pymysql.connect(host='localhost' ,port=3306 ,user='root', password='1234qwer', db='test', charset='utf8')
cursor = coon.cursor()
try:
cursor.execute(fun( sql))
data = cursor.fetchall()
coon.commit()
print(data)
except Exception as e:
coon.rollback()
print('运行', str(fun), '方法时出现错误,错误代码:', e)
finally:
cursor.close()
coon.close()
return run @openClose
def runSql(sql=None):
if sql is None:
sql = 'select * from students1'
return sql runSql()
runSql(‘select * from students1‘ where name= ‘tom1’)

添加时间记录功能

添加时间记录功能
def openClose(fun):
def run(sql=None):
coon =pymysql.connect(host='localhost' ,port=3306 ,user='root', password='1234qwer', db='test', charset='utf8')
cursor = coon.cursor()
try:
start_time = time.time()
cursor.execute(fun( sql))
data = cursor.fetchall()
coon.commit()
end_time = time.time()
print('持续时间:'+str(end_time - start_time))
print(data)
except Exception as e:
coon.rollback()
print('运行', str(fun), '方法时出现错误,错误代码:', e)
finally:
cursor.close()
coon.close()
return run @openClose
def runSql(sql=None):
if sql is None:
sql = 'select * from students1'
return sql runSql()
输出:

open_and_close_db 重要!重要!重要!

open_and_close_db  重要!重要!重要!

def open_and_close_db(do_sql):
def wrapper(sql='select * from students1'):
coon = pymysql.connect(host='localhost' ,port=3306 ,user='root', password='1234qwer', db='test', charset='utf8')
cursor = coon.cursor()
start_time = time.time()
do_sql(cursor, coon, sql)
cursor.close()
coon.close()
end_time = time.time()
print('持续时间:' + str(end_time - start_time))
return wrapper @open_and_close_db
def do_sql(cursor,coon,sql):
try:
cursor.execute(sql)
data = cursor.fetchall()
coon.commit()
print(data)
except Exception as e:
coon.rollback()
print('运行时出现错误,错误代码:', e) do_sql()
do_sql("update students1 set name = 'tom99999' where score = 44")

输出:

最新文章

  1. json的注意事项
  2. 夺命雷公狗----Git---5---分支
  3. Android开发之无线遥控器
  4. PHP移动文件指针ftell()、fseek()、rewind()总结
  5. xss漏洞挖掘小结
  6. Linux I2C总线控制器驱动(S3C2440)
  7. Python自动化 【第十篇】:Python进阶-多进程/协程/事件驱动与Select\Poll\Epoll异步IO
  8. iOS - AVPlayer 音视频播放
  9. Linux chmod
  10. #ifndef #define #endif 防止头文件被重复引用
  11. 关于No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=armv7 armv7s)使用百度地图的解决办法
  12. 对bootstrap不同版本的总结
  13. android - 解决“应用自定义权限重名”
  14. 远程调用服务框架-CXF(WebServic)
  15. 自定义的Config节点及使用
  16. SQL server 数据库的版本为661,无法打开,此服务器只支持655版及更低版本。不支持降级路径
  17. springboot项目部署云服务器
  18. angular 过滤器(日期转换,时间转换,数据转换等)
  19. IDEA的Maxcomputer Studio开发
  20. Ajax提交form表单内容和文件(jQuery.form.js)

热门文章

  1. 面试题:java内存中的堆区和数据结构中的堆有什么区别
  2. BBC评出的100本最具影响力经典书籍
  3. Ansible-目录
  4. 大数据集群环境搭建之一 hadoop-ha高可用安装
  5. prometheus学习系列十一: Prometheus 采集器的编写
  6. 定时任务工具Linux crontab命令详解
  7. MATLAB问题小集合
  8. DecimalField的使用
  9. Spring Cloud Stream 知识点
  10. AHOI2014 奇怪的计算器 和 HDU5306 Gorgeous Sequence