如何在python中测试数据库连接? [英] How to test database connectivity in python?

查看:689
本文介绍了如何在python中测试数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过MySQLdb库从python访问MySQL数据库.我正在尝试测试数据库连接,如下所示.

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!

推荐答案

我可能是错的(或者误解了您的问题:)),但是我认为与连接相关的异常会抛出在MySQLdb.connect()上.对于MySQLdb,要捕获的异常是MySQLdb.Error.因此,我建议将db设置移到try块内,并捕获适当的异常(MySQLdb.Error).另外,正如@JohnMee所提到的,如果没有结果,fetchone()将返回None,所以这应该起作用:

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

如果您不关心连接,而只是想测试查询的执行,我想您可以将连接设置留在try之外,但在您的例外中包括MySQLdb.Error,可能如下:

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.

这篇关于如何在python中测试数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆