简体   繁体   中英

perform validation or raise exception for incorrect user input in mysql python

I'm trying to perform validation in Crud operations in MySQL. My table has name,idno,division and I have wrote the MySQL output into a csv file. I'm giving a user input and if the user input matches with the idno in table then it should print the entire row. This works fine when I give the idno in the table but it doesn't raises exception when an incorrect value is given as input. Can anyone help me with raising exception or performing validation?

Here are my codes:

def search (self):

try:

    with open("test.csv", 'rb') as inputfile:

        reader = csv.DictReader(inputfile)
        user_input=int(raw_input("Enter the Idno to search:"))
        rows = [row for row in reader if row['Idno']==str(int(user_input)

        for row in rows:
            print rows


except ValueError:
    print "Enter correct idno "

search()

Here, to validate your user input from raw_input you can consider two ways - checking your value with regular expression - Checking with the actual database idno.

for example, before fetching actual data from database, check whether given idno is available or not using select query

Query: select idno from <table_name> and check for the existence. If not available, you can raise value error exception : raise ValueError

I take it that this line posted in your question

rows =  rows = [row for row in reader if row['Idno'] == str(int(user_input)

should really be

rows = [row for row in reader if row['Idno'] == str(int(user_input))]

You are checking this for a ValueError . Your exception will trap situations where the user inputs a value that is not an integer. But I take it that for an id number to be valid, it must also appear in your .csv file. Your code doesn't test for that. You need something like

rows = [row for row in reader if row['Idno'] == str(int(user_input))]
if not rows:
    raise ValueError("idno %r not found")

Or if, as your comments suggest, you have an objection to checking if the list is empty:

rows = [row for row in reader if row['Idno'] == str(int(user_input))]
if user_input not in rows:
    raise ValueError("idno %r not found")

Tried to perform validation using MySQL db and it works. But I dont know what should replace if result==() to make it more meaningful and perfect as () None doesn't works for me.

def search(self):

        user_input=raw_input('Enter idno:')

        cursor.execute("select * from table where Idno='{0}';".format(user_input))
        result=cursor.fetchall()

        if result==():
            print "User_input didnt match"

        else:
            print result
search()

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