|
| 1 | +import os # Used to access OS functionality, specifically to read environment variables (like DB credentials). |
| 2 | +from dotenv import load_dotenv # Loads environment variables from a .env file into os.environ for secure configuration. |
| 3 | +import tkinter as tk # The standard Python interface to the Tcl/Tk GUI toolkit, used to build the main application window and widgets. |
| 4 | +from tkinter import messagebox # A submodule of tkinter used specifically to display pop-up dialogs (e.g., error messages, warnings, info alerts). |
| 5 | +import pymysql # A pure-Python MySQL client library used to connect to and communicate with a MySQL database. |
| 6 | +import uuid # Used to generate Universally Unique Identifiers (UUIDs), often used for creating unique primary keys for database records. |
| 7 | +from input_validator import validate_student_data, sanitize_string # Input validation to prevent SQL injection |
| 8 | + |
| 9 | +load_dotenv() # 1. Load the secrets from the .env file |
| 10 | + |
| 11 | +# 2. Get the values safely |
| 12 | +# If the file is missing, these will be None |
| 13 | +DB_CONFIG = { |
| 14 | + 'host': os.getenv('DB_HOST'), |
| 15 | + 'port': int(os.getenv('DB_PORT', 3306)), # Default to 3306 if missing |
| 16 | + 'user': os.getenv('DB_USER'), |
| 17 | + 'password': os.getenv('DB_PASS'), |
| 18 | + 'database': os.getenv('DB_NAME'), |
| 19 | + 'cursorclass': pymysql.cursors.DictCursor |
| 20 | +} |
| 21 | +class StudentApp: |
| 22 | + def __init__(self, root): |
| 23 | + self.root = root |
| 24 | + self.root.title("🎓 Student Management System") |
| 25 | + self.root.geometry("600x500") |
| 26 | + |
| 27 | + # Title Label |
| 28 | + title_label = tk.Label(root, text="Student Marks Entry", font=("Arial", 18, "bold")) |
| 29 | + title_label.pack(pady=10) |
| 30 | + |
| 31 | + # --- FORM FRAME --- |
| 32 | + form_frame = tk.Frame(root) |
| 33 | + form_frame.pack(pady=10) |
| 34 | + |
| 35 | + # Name |
| 36 | + tk.Label(form_frame, text="Student Name:").grid(row=0, column=0, padx=5, pady=5) |
| 37 | + self.name_entry = tk.Entry(form_frame) |
| 38 | + self.name_entry.grid(row=0, column=1, padx=5, pady=5) |
| 39 | + |
| 40 | + # Roll No |
| 41 | + tk.Label(form_frame, text="Roll Number:").grid(row=1, column=0, padx=5, pady=5) |
| 42 | + self.roll_entry = tk.Entry(form_frame) |
| 43 | + self.roll_entry.grid(row=1, column=1, padx=5, pady=5) |
| 44 | + |
| 45 | + # --- MARKS FRAME --- |
| 46 | + marks_frame = tk.LabelFrame(root, text="Subject Marks") |
| 47 | + marks_frame.pack(fill="both", expand=True, padx=20, pady=10) |
| 48 | + |
| 49 | + self.subjects = ["Science", "Social", "Maths", "English", "Hindi", "Kannada"] |
| 50 | + self.entries = {} |
| 51 | + |
| 52 | + # Create input boxes for all subjects dynamically |
| 53 | + for i, sub in enumerate(self.subjects): |
| 54 | + tk.Label(marks_frame, text=sub).grid(row=i, column=0, padx=10, pady=5) |
| 55 | + entry = tk.Entry(marks_frame) |
| 56 | + entry.grid(row=i, column=1, padx=10, pady=5) |
| 57 | + self.entries[sub] = entry |
| 58 | + |
| 59 | + # Submit Button |
| 60 | + submit_btn = tk.Button(root, text="💾 Save to Database", command=self.save_data, |
| 61 | + bg="green", fg="white", font=("Arial", 12)) |
| 62 | + submit_btn.pack(pady=20) |
| 63 | + |
| 64 | + # Status Bar |
| 65 | + self.status_var = tk.StringVar() |
| 66 | + self.status_var.set("Ready to connect...") |
| 67 | + tk.Label(root, textvariable=self.status_var, bd=1, relief=tk.SUNKEN, anchor=tk.W).pack(side=tk.BOTTOM, fill=tk.X) |
| 68 | + |
| 69 | + def save_data(self): |
| 70 | + name = self.name_entry.get() |
| 71 | + roll_txt = self.roll_entry.get() |
| 72 | + |
| 73 | + # Collect marks as strings for validation |
| 74 | + marks_input = {} |
| 75 | + for sub_name in self.subjects: |
| 76 | + marks_input[sub_name] = self.entries[sub_name].get() |
| 77 | + |
| 78 | + # Validate all input data using the input validator |
| 79 | + is_valid, error_msg, validated_data = validate_student_data(name, roll_txt, marks_input) |
| 80 | + |
| 81 | + if not is_valid: |
| 82 | + messagebox.showerror("Validation Error", error_msg) |
| 83 | + return |
| 84 | + |
| 85 | + # Use validated and sanitized data |
| 86 | + name = validated_data['name'] |
| 87 | + roll_no = validated_data['roll_no'] |
| 88 | + marks = validated_data['marks'] |
| 89 | + |
| 90 | + # Connect to Database |
| 91 | + conn = None |
| 92 | + try: |
| 93 | + self.status_var.set("Connecting to server...") |
| 94 | + self.root.update_idletasks() # Force UI update |
| 95 | + |
| 96 | + conn = pymysql.connect(**DB_CONFIG) |
| 97 | + cursor = conn.cursor() |
| 98 | + |
| 99 | + # 1. Insert Student |
| 100 | + try: |
| 101 | + cursor.execute("INSERT INTO STUDENTS (ROLL_NO, NAME) VALUES (%s, %s)", (roll_no, name)) |
| 102 | + except pymysql.err.IntegrityError as e: |
| 103 | + # If error is 1062 (Duplicate), we just ignore it and move to marks |
| 104 | + if e.args[0] != 1062: |
| 105 | + raise e |
| 106 | + |
| 107 | + # 2. Insert Marks |
| 108 | + # Map names to IDs |
| 109 | + sub_ids = {"Science": 101, "Social": 102, "Maths": 103, "English": 104, "Hindi": 105, "Kannada": 106} |
| 110 | + |
| 111 | + for sub_name, marks_value in marks.items(): |
| 112 | + sub_id = sub_ids[sub_name] |
| 113 | + unique_id = str(uuid.uuid4()) |
| 114 | + |
| 115 | + cursor.execute(""" |
| 116 | + INSERT INTO MARKS (ID, ROLL_NO, SUBJ_ID, MARKS) |
| 117 | + VALUES (%s, %s, %s, %s) |
| 118 | + """, (unique_id, roll_no, sub_id, marks_value)) |
| 119 | + |
| 120 | + conn.commit() |
| 121 | + messagebox.showinfo("Success", f"Data saved for {name}!") |
| 122 | + self.status_var.set("Data Saved Successfully.") |
| 123 | + |
| 124 | + # Clear form |
| 125 | + self.name_entry.delete(0, tk.END) |
| 126 | + self.roll_entry.delete(0, tk.END) |
| 127 | + for e in self.entries.values(): |
| 128 | + e.delete(0, tk.END) |
| 129 | + |
| 130 | + except Exception as e: |
| 131 | + messagebox.showerror("Database Error", str(e)) |
| 132 | + self.status_var.set("Error occurred.") |
| 133 | + finally: |
| 134 | + if conn: conn.close() |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + root = tk.Tk() |
| 138 | + app = StudentApp(root) |
| 139 | + |
| 140 | + root.mainloop() |
0 commit comments