Advertisement
Guest User

Untitled

a guest
Nov 5th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # databaseModule.py
  3.  
  4. import  config
  5. import  MySQLdb
  6. import  traceback
  7. import  logging as logger
  8.  
  9. class  MyDB (object):
  10.     def  connect (self, user=config.DB_USER, password=config.DB_PASSWORD, \
  11.             host = config.DB_HOST, database=config.DB_DATABASE, unix_socket=config.UNIX_SOCKET):
  12.         if not  connection:
  13.             try:
  14.                 self.connection = MySQLdb.connect ()
  15.             except  mysql.connector.Error as err:
  16.                 logger.exception ('Database connection failed for ' + config.DB_USER + '@' + config.DB_HOST + '/' + config.DB_DATABASE)
  17.                 exit ()
  18.  
  19.     def  execute (self, sql, *args):
  20.         retval =  None
  21.         try:
  22.             cursor = self.connection.cursor ()
  23.             retval = cursor.execute (sql, *args) # when you pass a tuple to this method execute get it as is
  24.             self.cursor.fetchall ()
  25.         except  ( AttributeError, MySQLdb.OperationalError ):
  26.             logger.exception ('Connection finished. Retrying connection')
  27.             self.connect ()
  28.             self.connection.commit ()
  29.             self.execute (sql, *args)
  30.         except  MySQLdb.Error:
  31.             logger.exception ('Execution error')
  32.             self.connection.rollback ()
  33.             raise
  34.         return retval #, self.cursor () return also cursor. Return value with dictionary
  35.  
  36.     def  query (self, sql, *args):
  37.         retval = None
  38.         try:
  39.             retval = self.execute (sql)
  40.         except  ( AttributeError, MySQLdb.OperationalError ):
  41.             logger.exception ('Connection finished. Retrying connection')
  42.             self.connect ()
  43.             self.query (sql, *args)
  44.         except  MySQLdb.Error:
  45.             logger.exception ('Execution error')
  46.             self.connection.rollback ()
  47.             raise
  48.         return  retval
  49.  
  50.     def  commit (self):
  51.         self.connection.commit ()
  52.  
  53.     def  disconnect (self):
  54.         self.connection.close ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement