How to test database connectivity in python?

孤者浪人 提交于 2020-01-02 00:54:10

问题


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!


回答1:


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 is MySQLdb.Error. Therefore, I would suggest moving the db setup inside of the try 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:

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 are just looking to test the execution of the query, I guess you could leave the connection setup outside the 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 would at least give you a more detailed reason of why it failed.




回答2:


Yes. Looks good to me.

My personal preferences:

  • actually throw an exception if no connection
  • you only need to fetchone, the test for None is superfluous (unless you're keen to enforce a minimum version of the database)


来源:https://stackoverflow.com/questions/11735371/how-to-test-database-connectivity-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!