Skip to main content
 首页 » 编程设计

Python-MySQLdb,如何访问 `OperationalError` 中的异常错误代码

2025年02月15日21arxive

我需要捕获特定的 OperationalError 异常。异常文本使用错误代码 2006。该库在 MySQLdb.constants.CR.SERVER_GONE_ERROR = 2006 处定义错误代码。

如何从异常中获取错误代码?

当我检查 MySQLdb._mysql_exceptions 时,有一个 OperationalError 异常的定义,但它没有构造函数或如何访问异常错误代码的描述。

请您参考如下方法:

您可以像下面这样捕获错误号:

try: 
            # Adding field 'Bug.bize_size_tag_name' 
            db.add_column('search_bug', 'bize_size_tag_name', orm['search.bug:bize_size_tag_name']) 
except MySQLdb.OperationalError, errorCode: 
            if errorCode[0] == 1060: 
                pass 
            else: 
                raise 

引用:https://www.programcreek.com/python/example/2584/MySQLdb.OperationalError