我目前正在开发一个数据库应用程序,用户在其中填写客户表单,然后将数据添加到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()
试着这样做:
这里
True
将仅在行中没有错误时返回,否则False
将返回,因此基于此,您在AddCustomer()
内创建一个if
。我还将execute
的参数更改为tuple
,而不是按惯例更改为list
相关问题 更多 >
编程相关推荐