如何在 python 中进行验证?

How to do validation in python?

我正在使用 python tkinter 和 sqlite3 为员工管理系统制作一个图形用户界面。 在此用户界面中,用户可以添加、查看、删除和更新员工信息。

def save():
    con = None
    try:
        con = connect("pro.db")
        cursor = con.cursor()
        sql = "insert into Employee values('%d', '%s', '%f')"
        id = int(aw_ent_id.get())
        name = aw_ent_name.get()
        lenstring = False
        while not lenstring:
            if len(name) >= 2:
                lenstring = True    
            else:
                showerror("error","Enter atleast 2 letters")
                break
        salary = float(aw_ent_salary.get())
        cursor.execute(sql%(id, name, salary))
        con.commit()
        showinfo("success", "record added")
        aw_ent_id.delete(0, END)
        aw_ent_name.delete(0, END)
        aw_ent_salary.delete(0, END)
        aw_ent_id.focus()
    except Exception as e:
        con.rollback()
        showerror("issue", e)
    finally:
        if con is not None:
            con.close()

代码是 运行,但我在验证姓名和薪水时遇到一些错误。 对于名称,我已经完成验证但它不起作用。我收到一个错误

  1. 即使出现错误,数据也会被保存。 我应该怎么做才能让它正确?

最好是:

  • 在保存到数据库之前验证输入
  • 如果 len(name) 小于 2 则抛出异常而不是使用 while 循环检查(实际上 while 循环是没有意义的)
  • 使用占位符避免SQL注入

以下更新save():

# avoid using wildcard import
import tkinter as tk
from tkinter.messagebox import showinfo, showerror
import sqlite3

...

def save():
    con = None
    try:
        # validate inputs
        # use emp_id instead of id because id is built-in function
        emp_id = int(aw_ent_id.get().strip()) # raise ValueError if not a valid integer
        name = aw_ent_name.get().strip()
        if len(name) < 2:
            raise Exception('Name too short, at least 2 letters')
        salary = float(aw_ent_salary.get().strip()) # raise ValueError if not a valid float number
        # validations on inputs are passed, try saving to database
        sql = 'insert into Employee values (?, ?, ?)'  # use placeholders to avoid SQL injection
        con = sqlite3.connect('pro.db')
        cursor = con.cursor()
        cursor.execute(sql, (emp_id, name, salary))
        con.commit()
        showinfo('Success', 'Employee added')
        aw_ent_id.delete(0, tk.END)
        aw_ent_name.delete(0, tk.END)
        aw_ent_salary.delete(0, tk.END)
        aw_ent_id.focus_set()
    except Exception as e:
        if con:
            con.rollback()
        showerror("Error", e)
    finally:
        if con:
            con.close()

...