【发布时间】:2021-07-10 23:15:30
【问题描述】:
我目前正在开发一个数据库应用程序,用户填写客户表格并将数据添加到 SQLite3 表中。我正在尝试向我的代码添加验证,并且它可以正常工作,但是它将记录添加到包含无效数据的表中。如果数据无效,有什么方法可以停止代码的执行?请看下面的代码和界面截图:
def validate(self):
dateofbirth = self.DOBEntry.get()
try:
datetime.datetime.strptime(dateofbirth, '%D/%M/%Y')
except ValueError:
tkinter.messagebox.showerror("Error","Please enter the date of birth in the correct format DD-MM-YYYY")
def AddCustomer(self):
customerid = int(self.CustomerEntry.get())
branchid = self.BranchEntry.get()
name = self.NameEntry.get()
surname = self.SurnameEntry.get()
dateofbirth = self.DOBEntry.get()
town = self.TownEntry.get()
postcode = self.PostcodeEntry.get()
email = self.EmailEntry.get()
telephone = self.TelephoneEntry.get()
medical = self.MedicalEntry.get()
try:
self.validate()
with sqlite3.connect("LeeOpt.db") as db:
cursor = db.cursor()
add_customer = ('''INSERT INTO Customer(CustomerID, BranchID, Name, Surname, DateOfBirth, Town, Postcode, EmailAddress, TelephoneNo, MedicalConditions)
VALUES (?,?,?,?,?,?,?,?,?,?)''')
cursor.execute(add_customer, [(customerid),(branchid),(name),(surname),(dateofbirth),(town),(postcode),(email),(telephone),(medical)])
tkinter.messagebox.showinfo("Notification","Customer added successfully")
self.ClearEntries()
except (sqlite3.IntegrityError):
tkinter.messagebox.showerror("Error","This CustomerID is already taken, please try another.")
self.ClearID()
【问题讨论】:
-
什么是无效数据?
-
只需让
validate返回True或False,然后在更新记录之前检查该值。或者,让validate在显示对话框后重新引发异常。 -
@CoolCloud 一个不符合函数中规定格式的日期。
-
我认为将
self.validate放在try内部并不好,因为无论如何都不会显示任何错误,因为您跳过了函数中的错误。所以我认为最好从函数中返回True或False并检查if self.validate():然后继续。 -
@CoolCloud 请原谅我的无知,我是Python初学者,如何返回
True或False?。我做了一些研究,但无法理解它。
标签: python database sqlite validation tkinter