简体   繁体   English

如何在 Python 中处理 mySQL 异常?

[英]How do I handle mySQL exceptions in Python?

I would like to ask how do I handle MySQL exceptions in Python.我想问一下如何在 Python 中处理 MySQL 异常。 Basically, my program asks for the number of descriptions they would like to enter and I have an if statement to check that the number they have entered does not exceed 10. However, the column in my database called "Description" only allows 100 characters.基本上,我的程序要求他们输入描述的数量,我有一个 if 语句来检查他们输入的数量不超过 10。但是,我的数据库中名为“描述”的列只允许 100 个字符。 Thus, the total number of chars entered by the user cannot exceed 100 chars, however, I cannot catch the exception.因此,用户输入的字符总数不能超过 100 个字符,但是,我无法捕获异常。 I have looked at multiple online resources such as importing "mysql.connector" and tried catching the DataError exception but it is still not working.我查看了多个在线资源,例如导入“mysql.connector”并尝试捕获 DataError 异常,但它仍然无法正常工作。 I also tried specifying the exact exception but it still gives the same error when I try to test entering characters more than 100. Does anyone know any possible ways I can address this?我也尝试指定确切的异常,但是当我尝试测试输入超过 100 个字符时它仍然会出现相同的错误。有谁知道我可以解决这个问题的任何可能方法吗?

My end goal is to print out the cause of the error to the user and inform them that they cannot enter more than 100 characters and prevent the program from stopping abruptly.我的最终目标是向用户打印出错误原因并告知他们不能输入超过 100 个字符并防止程序突然停止。 Thank you.谢谢你。

Below are some snapshots of my code and the exception I am trying to catch.下面是我的代码的一些快照和我试图捕获的异常。

My Code我的代码

Exception encountered and trying to catch遇到异常并试图捕获

The exception you need to catch is in the last line of your "Exception encountered and trying to catch" image.您需要捕获的异常位于“遇到异常并试图捕获”图像的最后一行。

The exception is of type "mysql.connector.error.DataError".异常类型为“mysql.connector.error.DataError”。

In your first image you are catching "mysql.connector.DataError".在您的第一张图片中,您捕获了“mysql.connector.DataError”。 You are missing an "error."你错过了一个“错误”。 in between.之间。

Your code seems to be incomplete, so I am assuming this is what you are looking for.您的代码似乎不完整,所以我假设这就是您要找的。 From the MySQL Connector/Python Developer Guide, section 10.12.2 errors.Error Exception , I propose the following solution:从 MySQL 连接器/Python 开发人员指南, 第 10.12.2 节 errors.Error Exception ,我提出以下解决方案:

import mysql.connector

... ...

while True:
    try:
        number_of_description = int(input("Enter the number of descriptions you would like to give the item: "))
    except ValueError:
        print("You cannot enter a non-number value. Please try again.")
    except mysql.connector.Error as err:
        if err.errno == 1406:
            print('DataError: This exception is raised when there were problems with the data.')
            continue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM