Django / Python: catch MySQL IntegrityError

随声附和 提交于 2021-02-08 03:36:54

问题


In Django/Python, how do I catch a specific mySQL error: 'IntegrityError':

try:
   cursor.execute(sql)
except IntegrityError:
    do_something

Not sure what I should import and from where.


回答1:


DId you try from django.db import IntegrityError? First result for me in Google btw. when searching for IntegrityError.




回答2:


Here is a similar response . In summary

from django.db import IntegrityError
from django.shortcuts import render_to_response

try:
# code that produces error
except IntegrityError as e:
return render_to_response("template.html", {"message": e.message})


来源:https://stackoverflow.com/questions/14769988/django-python-catch-mysql-integrityerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!