python - Python中出生日期的格式检查
问题描述
我目前正在开发一个数据库应用程序,用户填写客户表格并将数据添加到 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()
解决方案
尝试这样的事情:
def validate(self):
dateofbirth = self.DOBEntry.get()
try:
datetime.datetime.strptime(dateofbirth, '%D/%M/%Y')
return True # returns a boolean True
except ValueError:
tkinter.messagebox.showerror("Error","Please enter the date of birth in the correct format DD-MM-YYYY")
return False
def AddCustomer(self):
# Same code
if self.validate(): # If true is returned, then...also same as if self.validate()==True
try:
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
只有当行中没有错误时才会返回here ,否则False
将返回,因此基于此,您创建一个if
inside AddCustomer()
。我还将您的参数更改为execute
atuple
而不是 a list
,因为它是惯例。
推荐阅读
- javascript - 使用 JavaScript,如果 URL 中提供了 id,我如何突出显示标签
- linux - 为位于我的一个文件夹中的 shell 脚本设置别名
- dask - 如何在 Dask 分布式 SSHCluster 中正确设置工作端口?
- node.js - Typescript Nodejs Dockerfile:错误 TS5057:在指定目录中找不到 tsconfig.json 文件:“。”
- django - 尝试将外键字段编辑到另一个模型中的一个模型
- docker - 通过 OpenVPN docker 路由流量
- c - 将 const *char 传递给 strlen() 表示我正在传递 unsigned long
- c# - 如何拥有具有多个精灵的游戏对象预制件?
- java - 如何比较 Java 中的两个日期,然后将结果与另一个日期进行比较?
- android - 将 min SDK 从 21 增加到 24 时,APK 大小增加了 35mb