我正在尝试在MySQL中的Crud操作中执行验证。我的表有name,idno,division,我把MySQL输出写入csv文件。我正在给用户输入,如果用户输入与表中的idno匹配,那么它应该打印整行。 当我在表中给出idno时这很好,但是当输入的值不正确时它不会引发异常。任何人都可以帮助我提高异常或执行验证吗?
以下是我的代码:
def搜索(自我):
Country
搜索()
答案 0 :(得分:0)
在此,要验证来自raw_input
的用户输入,您可以考虑两种方式
- 使用正则表达式检查您的值
- 检查实际的数据库idno。
例如,在从数据库中获取实际数据之前,使用select query检查给定的idno是否可用
查询:select idno from <table_name>
并检查是否存在。如果不可用,则可能引发值错误
例外:raise ValueError
答案 1 :(得分:0)
我认为你在问题中发布了这一行
rows = rows = [row for row in reader if row['Idno'] == str(int(user_input)
应该是
rows = [row for row in reader if row['Idno'] == str(int(user_input))]
您正在检查此ValueError
。您的异常将捕获用户输入非整数值的情况。但我认为,如果ID号有效,它也必须出现在.csv
文件中。您的代码不会测试它。你需要像
rows = [row for row in reader if row['Idno'] == str(int(user_input))]
if not rows:
raise ValueError("idno %r not found")
或者,如果您的意见建议,您反对检查列表是否为空:
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")
答案 2 :(得分:0)
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()