Home > Blockchain >  How to do validation in python?
How to do validation in python?

Time:10-18

I am making a gui for employee management system using python tkinter and sqlite3. In this gui user can add, view, delete amd update employee info.

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()

the code is running but i am getting some errors in validating name and salary. for name i have done validating but its not working. I am getting an error

  1. the data is getting saved even after getting error. What should i do to make it right?

CodePudding user response:

It is better to:

  • validate the inputs before saving to database
  • raise exception if len(name) is less than 2 instead of using while loop checking (actually the while loop is meaningless)
  • use placeholders to avoid SQL injection

Below is updated 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()

...
  • Related