I have a custom class written in python to re-establish a mysql connection, if the current connection is dead. The only problem is, the current one always seems to be dead and is always entering into the except block of my try-except.
class DB:
conn = None
def connect( self ):
try:
self.conn = MySQLdb.connect("localhost", "xxxx", "xxxxxx", "Systems")
except ( AttributeError, Mysqldb.OperationalError ), e:
raise e
def query( self, sql, params ):
try:
cursor = self.conn.cursor()
cursor.execute( sql, ( params ) )
except ( AttributeError, MySQLdb.OperationalError ), e:
print 'exception generated during sql connection: ', e
self.connect()
cursor = self.conn.cursor()
cursor.execute( sql, ( params ) )
cursor.close()
return cursor
def close( self ):
try:
if self.conn:
self.conn.close()
print '...Closed Database Connection: ' + self.conn
else:
print '...No Database Connection to Close.'
except ( AttributeError, MySQLdb.OperationalError ), e:
raise e
db = DB()
db.query( sql, myParams )
The problem is two-fold. 1) When I call db.close() I get ...No Database Connection output. 2) Each time I execut db.query( sql, myParams ) it enters the except clause and outputs exception generated during sql connection:
It seems like my db connection is closing itself after each query call. But I don't know why this would be happening. Any help on this issue would be greatly appreciated.