首页 > 解决方案 > 如何访问 MySQL python 库异常中的错误代码

问题描述

我使用这个问题的代码来捕获操作错误:Python-MySQLdb,你如何访问 `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

但是我无法访问错误代码。我得到错误:

  File "main.py", line 835, in db_execute
    if errorCode[0] == 1213:
TypeError: 'OperationalError' object does not support indexing

标签: pythonmysqlpython-3.xerror-handlingmysql-python

解决方案


感谢@roganjosh 对问题的评论,我发现了 OperationalError 的属性:

['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', '__weakref__', 'args', 'with_traceback']

错误代码在属性中args[0]


推荐阅读