简体   繁体   中英

How do I handle mySQL exceptions in Python?

I would like to ask how do I handle MySQL exceptions in Python. 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. Thus, the total number of chars entered by the user cannot exceed 100 chars, however, I cannot catch the exception. I have looked at multiple online resources such as importing "mysql.connector" and tried catching the DataError exception but it is still not working. 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?

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. 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".

In your first image you are catching "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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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