I am accessing a MySQL database from python via MySQLdb library. I am attempting to test the database connection as shown below.
db = MySQLdb.connect(self.server, self.user,
self.passwd, self.schema)
cursor = db.cursor()
try:
cursor.execute("SELECT VERSION()")
results = cursor.fetchone()
ver = results[0]
if (ver is None):
return False
else:
return True
except:
print "ERROR IN CONNECTION"
return False
Is this the right way one should test the connectivity when writing unit testcases? If there is a better way, please enlighten!
I could be wrong (or misinterpreting your question :) ), but I believe the a connection-related exception gets thrown on
MySQLdb.connect()
. With MySQLdb, the exception to catch isMySQLdb.Error
. Therefore, I would suggest moving thedb
setup inside of thetry
block and catching the proper exception (MySQLdb.Error
). Also, as @JohnMee mentions,fetchone()
will return None if there are no results, so this should work:If you don't care about the connection and are just looking to test the execution of the query, I guess you could leave the connection setup outside the
try
but includeMySQLdb.Error
in your exception, perhaps as follows:This would at least give you a more detailed reason of why it failed.
Yes. Looks good to me.
My personal preferences: