无法在Python中捕获MySQL IntegrityError

我使用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异常.为什么在后一种情况下没有发现异常?

最佳答案
问题是我抓到了不正确的异常.

事实证明,引发的错误实际上是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: MysqL.err.IntegrityError'>

相关文章

优化MySQL数据库发布系统存储的方法有:1.mysql库主从读写分...
使用mysql的方法:在“我的电脑”→右键→“管理”→“服务”...
在mysql中查看root用户权限的方法:1.命令行启动mysql服务;...
MySQL主从复制是用来备份一个与主数据库一样环境的从数据库,...
运行mysql的方法1.启动mysql服务,在“我的电脑”→右键→“...
开启mysql的方法1.可以通过快捷键win+r,输入cmd,打开窗口,...