I could be wrong (or misinterpreted your question :)), but I believe that the connection-related exception is thrown at MySQLdb.connect()
. With MySQLdb, the exception for catch is MySQLdb.Error
. Therefore, I would suggest moving the db
settings inside the try
block and MySQLdb.Error
correct exception ( MySQLdb.Error
). Also, as @JohnMee mentions, fetchone()
returns None if there are no results, so this should work:
try: db = MySQLdb.connect(self.server, self.user, self.passwd, self.schema) cursor = db.cursor() cursor.execute("SELECT VERSION()") results = cursor.fetchone() # Check if anything at all is returned if results: return True else: return False except MySQLdb.Error: print "ERROR IN CONNECTION" return False
If you donβt care about the connection and just want to check the execution of the request, I think you can leave the connection settings outside of try
, but include MySQLdb.Error
in your exception, perhaps as follows:
db = MySQLdb.connect(self.server, self.user, self.passwd, self.schema) cursor = db.cursor() try: cursor.execute("SELECT VERSION()") results = cursor.fetchone() # Check if anything at all is returned if results: return True else: return False except MySQLdb.Error, e: print "ERROR %d IN CONNECTION: %s" % (e.args[0], e.args[1]) return False
This, at least, will give you a more detailed reason why this failed.
source share