Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- # databaseModule.py
- import config
- import MySQLdb
- import traceback
- import logging as logger
- class MyDB (object):
- def connect (self, user=config.DB_USER, password=config.DB_PASSWORD, \
- host = config.DB_HOST, database=config.DB_DATABASE, unix_socket=config.UNIX_SOCKET):
- if not connection:
- try:
- self.connection = MySQLdb.connect ()
- except mysql.connector.Error as err:
- logger.exception ('Database connection failed for ' + config.DB_USER + '@' + config.DB_HOST + '/' + config.DB_DATABASE)
- exit ()
- def execute (self, sql, *args):
- retval = None
- try:
- cursor = self.connection.cursor ()
- retval = cursor.execute (sql, *args) # when you pass a tuple to this method execute get it as is
- except ( AttributeError, MySQLdb.OperationalError ):
- logger.exception ('Connection finished. Retrying connection')
- self.connect ()
- self.connection.commit ()
- self.execute (sql, *args)
- except MySQLdb.Error:
- logger.exception ('Execution error')
- self.connection.rollback ()
- raise
- return {'retval': retval, 'cursor': cursor}
- def query (self, sql, *args):
- retval = None
- try:
- cursor = self.connection.cursor ()
- retval = cursor.execute (sql)
- except ( AttributeError, MySQLdb.OperationalError ):
- logger.exception ('Connection finished. Retrying connection')
- self.connect ()
- self.query (sql, *args)
- except MySQLdb.Error:
- logger.exception ('Execution error')
- self.connection.rollback ()
- raise
- return {'retval': retval, 'cursor': cursor}
- def commit (self):
- self.connection.commit ()
- def disconnect (self):
- self.connection.close ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement