【问题标题】:cannot catch MySQL IntegrityError in Python无法在 Python 中捕获 MySQL IntegrityError
【发布时间】:2015-01-23 23:48:01
【问题描述】:

我正在将 Python/Bottle/SqlAlchemy/MySQL 用于 Web 服务。

我试图捕捉通过调用存储过程引发的IntegrityError,但我无法做到。

使用这个

cursor = connection.cursor()
cursor.callproc('my_stored_proc', [arguments])

产生与

相同的结果
try:
    cursor = connection.cursor()
    cursor.callproc('my_stored_proc', [arguments])
except IntegrityError as e:
    print("Error: {}".format(e))
    return {"message": e.message}

在这两种情况下,我都会收到 IntegrityError 异常。为什么后一种情况没有捕获到异常?

【问题讨论】:

  • 您如何/何时提交交易? IntegrityError 可能会在事务提交时引发,而不是在调用存储过程时引发。

标签: python mysql exception stored-procedures sqlalchemy


【解决方案1】:

问题是我捕捉到了错误的异常。

事实证明,引发的错误实际上是 pymysql.err.IntegrityError 类型,而不是我假设的 sqlalchemy.exc.IntegrityError

我通过以下方式发现了异常类型:

import sys
try:
    cursor = connection.cursor()
    cursor.callproc('my_stored_proc', [arguments])
except:
    print "Unexpected error:", sys.exc_info()[0]

我看到了这个打印输出:

Unexpected error: <class 'pymysql.err.IntegrityError'>

【讨论】:

  • 只是补充一下,因为我遇到了类似的问题。我也抓不住。我不得不导入 pymysql;除了 pymysql.IntegrityError;
【解决方案2】:

在我和你的情况下,你会使用 sqlalchemy 对象:

try:
    cursor = connection.cursor()
    cursor.callproc('my_stored_proc', [arguments])
except sqlalchemy.exc.IntegrityError as e:
    print("Error: {}".format(e))
    return {"message": e.message}

【讨论】:

    【解决方案3】:

    就我而言,这可能对您也有帮助,我使用 MYSQL 作为数据库,因此要捕获异常,我需要导入异常

    from django.db.utils import IntegrityError
    

    那你可以试试这样抓

    try:
        #your code
    except IntegrityError:
        #your code when integrity error comes
    

    【讨论】:

    • OP 询问的是 pymysql,而不是 Django。
    猜你喜欢
    • 1970-01-01
    • 2014-08-22
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多