Python operates on the database, and the decorator manages the opening and closing of the database.

import pymysql
class ConDb():
    def openClose(fun):
        def run(self,sql=None):
            #create database connection
            db=pymysql.connect(host='localhost',port=3306 ,user='root',password='root',db='ljj',charset='utf8')
            #create cursor
            cursor = db.cursor()
            try:
                #Run sql statement
                cursor.execute(fun(self,sql))
                # get the return value
                li=cursor.fetchall()
                #Commit transaction
                db.commit()
            except Exception as e:
                #If there is an error, roll back the transaction
                db.rollback()
                # print error message
                print('Running',str(fun),'An error occurred, error code:',e)
            finally:
                #Close the cursor and database connection
                cursor.close()
                db.close()
            try:
                #Return sql execution information
                return li
            except:
                print('No return value, please check the code, the information appears in the decorator method in the ConDb class')
        return run


    @openClose
    def runSql(self,sql=None):
        if sql is None:
            sql='select * from batch'
        return sql

    @openClose
    def runSql1(self,sql=None):
        return sql

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325801058&siteId=291194637