Simple encapsulation pymysql

pymysql Import 
from the Common Import dir_config 
from Common.readconfig Import readconfig 
Import the logging 
from the Common Import Logger 
class DoMysql: 
    DEF the __init __ (Self): 
        . self.config = readconfig () read_config (dir_config.db_config_path, "DB", "Config") 
        the logging .info ( "start connecting to the database") 
        the try: 
            self.db = pymysql.connect (** self.config) 
            logging.info ( "database successfully connected") 
        the except: 
            logging.info ( "database connection failed") 
            The raise 

    DEF ExecQuery (Self, SQL): 
        '' ' 
        execute a query 
        : param SQL: 
        : return:
        '''
        cursor = self.db.cursor()
        the try: 
            cursor.execute (sql) # execute sql, 
            logging.info ( "the successful implementation of sql") 
        the except: 
            logging.info ( "failure to perform sql") 
            The raise 
        # cursor.fetchone RES = () # returns a single one yuan group 
        res = cursor.fetchall () # multiple returns a nested list of tuples 
        # turned off to switch off connection cursor 
        cursor.close () 
        self.db.close () 
        logging.info ( "execution result return value: { } 0 "the format (RES)). 
        return RES 

    DEF ExecNonQuery (Self, SQL): 
        '' ' 
        execute non query 
        : param SQL: 
        : return: 
        ' '' 
            the cursor.execute (SQL) 
        Cursor = self.db .cursor()
        the try: 
            logging.info ( "the successful implementation of sql") 
        the except: 
            logging.info ( "failure to perform sql") 
            The raise 
        # the commit () method: in the database to add, delete, change of time, must be submitted, or the inserted data does not take effect. 
        self.db.commit () 
        cursor.close () 
        self.db.close ()

  

Guess you like

Origin www.cnblogs.com/l7planet/p/11572004.html