首页 > 数据库技术 > 详细

pymysql装饰器封装

时间:2019-12-08 22:14:44      阅读:153      评论:0      收藏:0      [点我收藏+]

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")

输出:

技术分享图片

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

技术分享图片

 

pymysql装饰器封装

原文:https://www.cnblogs.com/111testing/p/12007249.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!