pymysql operation mysql package

1  import pymysql
 2  from lib.logger import logger
 3  from warnings import filterwarnings
 4 filterwarnings ( " ignore " , category = pymysql.Warning) # ignore mysql warning message
 5  
6  class MysqlDb ():
 7  
8      logger = logger
 9  
10      def  __init__ ( Self, Host, Port, User, the passwd):
 . 11          # database connection 
12 is          self.conn = pymysql.connect (
 13 is              Host =Host,
 14              Port = Port,
 15              User = User,
 16              the passwd = the passwd,
 . 17              charset = ' UTF8 ' 
18 is          )
 . 19          # create a cursor object via cursor (), and outputs the result to the query so that dictionary format 
20 is          self.cur = Self. conn.cursor (the cursor = pymysql.cursors.DictCursor)
 21  
22      DEF  __del__ (Self): # trigger is released target resources, and finally the operation when an object about to be deleted 
23          # close the cursor 
24-          self.cur.close ()
 25          # close the database connection 
26         self.conn.close ()
 27  
28      def select_db (self, db_name):
 29          "" " 
30          select database
 31          : return:
 32          " "" 
33          try :
 34              self.conn.select_db (db_name)
 35              self.logger.logger .info ( " Select {0} executed successfully " .format (db_name))
 36          except Exception as e:
 37              self.logger.logger.exception ( " Operation error: {0} " .format (e))
 38  
39      def query_db (self, sql, state = "All " ):
 40          " "" 
41 is          query
 42 is          : param sql: sql statement
 43 is          : param State: All Search, outhor single query
 44 is          : return:
 45          "" " 
46 is          # performed using sql Execute () 
47          self.logger. logger.info (SQL)
 48          self.cur.execute (SQL)
 49          IF State == " All " :
 50              # use or fetchall () Gets the query result 
51 is              Data = self.cur.fetchall ()
 52 is          the else :
 53 is              Data =self.cur.fetchone ()
 54 is          return Data
 55  
56 is      DEF execute_db (Self, SQL):
 57 is          "" " update / insert / delete " "" 
58          the try :
 59              # use execute () Executes SQL 
60              self.cur.execute ( SQL)
 61 is              # commit the transaction 
62 is              self.conn.commit ()
 63 is              self.logger.logger.info ( " {0} successfully executed " .format (SQL))
 64          the except Exception AS E:
 65              self.logger.logger.exception ( " Operation error: {} ".format (E))
 66              # roll back all changes 
67              self.conn.rollback ()
 68  
69  IF  __name__ == ' __main__ ' :
 70      Pass

 

Guess you like

Origin www.cnblogs.com/tython/p/12701392.html