0% found this document useful (0 votes)
37 views14 pages

Student Records Management System

The document is a Python script for a Student Data Records System that connects to a MySQL database. It allows users to perform various operations such as adding, modifying, deleting, searching, viewing, sorting, and filtering student records, as well as exporting data to CSV. The script includes a main menu for user interaction and handles database connections and queries efficiently.

Uploaded by

MANAV VERMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views14 pages

Student Records Management System

The document is a Python script for a Student Data Records System that connects to a MySQL database. It allows users to perform various operations such as adding, modifying, deleting, searching, viewing, sorting, and filtering student records, as well as exporting data to CSV. The script includes a main menu for user interaction and handles database connections and queries efficiently.

Uploaded by

MANAV VERMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Source Code

import [Link]
import os
import csv
from tabulate import tabulate

print("\n=================================================")
print("---<<Welcome to Student Data Records System!>>---")
print("=================================================\n")

# Function to establish a database connection


def create_connection():
connection = [Link](
host="localhost",
user="root",
password="1213"
)
return connection

# Function to create a database if it doesn't exist


def create_database(cursor, database_name):
create_database_query = f"CREATE DATABASE IF NOT EXISTS
{database_name}"
[Link](create_database_query)
print(f"Using database: {database_name}")

# Function to create a table if it doesn't exist


def create_table(connection):
cursor = [Link]()
create_table_query = """
CREATE TABLE IF NOT EXISTS students (
rollno INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
marks FLOAT,
gender ENUM('Male', 'Female', 'Other'),
dob DATE,
address TEXT
)
"""
[Link](create_table_query)
[Link]()

def show_databases_and_tables(connection):
while True:
cursor = [Link]()
# Fetch and display databases
[Link]("SHOW DATABASES")
databases = [database[0] for database in [Link]()]

headers_databases = ["Databases"]
table_data_databases = [[database] for database in databases]

print("\nDatabases:")
print(tabulate(table_data_databases, headers=headers_databases,
tablefmt="pretty"))

# Fetch and display tables


print("\nTables:")
print("=======")
[Link]("SHOW TABLES FROM studentrec")
tables = [table[0] for table in [Link]()]

headers_tables = ["Tables"]
table_data_tables = [[table] for table in tables]

print(tabulate(table_data_tables, headers=headers_tables,
tablefmt="pretty"))
choice = input("Do you want to move the main menu (y/n)?
").lower()
if choice == 'y':
break

def add_record(connection):
while True:
rollno = int(input('Enter rollno: '))
name = input('Enter name: ')
marks = float(input('Enter marks: '))
gender = input('Enter gender (Male/Female/Other): ')
dob = input('Enter date of birth (YYYY-MM-DD): ')
address = input('Enter address: ')

cursor = [Link]()
insert_query = "INSERT INTO students (rollno, name, marks,
gender, dob, address) VALUES (%s, %s, %s, %s, %s, %s)"
data = (rollno, name, marks, gender, dob, address)
[Link](insert_query, data)
[Link]()
print("Record Saved")

choice = input("Do you want to add another record (y/n)?


").lower()
if choice != 'y':
break

def modify_record(connection):
while True:
print("Modify a Record")
print("================")
rollno = int(input('Enter rollno you want to modify: '))

select_query = "SELECT * FROM students WHERE rollno = %s"


data = (rollno,)

cursor = [Link]()
[Link](select_query, data)

record = [Link]()

if record:
print("Rollno=", record[0])
print("Name=", record[1])
print("Marks=", record[2])
print("Gender=", record[3])
print("DOB=", record[4])
print("Address=", record[5])

choice = input("Do you want to modify this record (y/n):


").lower()

if choice == 'y':
new_rollno = int(input('Enter new rollno: '))
new_name = input('Enter new name: ')
new_marks = float(input('Enter new marks: '))
new_gender = input('Enter new gender (Male/Female/Other):
')
new_dob = input('Enter new date of birth (YYYY-MM-DD): ')
new_address = input('Enter new address: ')

update_query = "UPDATE students SET rollno=%s, name=%s,


marks=%s, gender=%s, dob=%s, address=%s WHERE rollno=%s"
data = (new_rollno, new_name, new_marks, new_gender,
new_dob, new_address, rollno)
[Link](update_query, data)
[Link]()
print("Record Modified")
else:
print("Record not found")

choice = input("Do you want to modify another record (y/n)?


").lower()
if choice != 'y':
break

def delete_record(connection):
while True:
print("Delete a Record")
print("================")
rollno = int(input('Enter rollno you want to delete: '))

select_query = "SELECT * FROM students WHERE rollno = %s"


data = (rollno,)

cursor = [Link]()
[Link](select_query, data)

record = [Link]()

if record:
print("Rollno=", record[0])
print("Name=", record[1])
print("Marks=", record[2])
print("Gender=", record[3])
print("DOB=", record[4])
print("Address=", record[5])

choice = input("Do you want to delete this record (y/n):


").lower()
if choice == 'y':
delete_query = "DELETE FROM students WHERE rollno = %s"
data = (rollno,)
[Link](delete_query, data)
[Link]()
print("Record Deleted")
else:
print("Record not found")

choice = input("Do you want to delete another record (y/n)?


").lower()
if choice != 'y':
break

def search_record(connection):
while True:
print("Search a Record")
print("===================")
rollno = int(input('Enter rollno you want to search: '))

select_query = "SELECT * FROM students WHERE rollno = %s"


data = (rollno,)

cursor = [Link]()
[Link](select_query, data)

record = [Link]()

if record:
headers = ["Rollno", "Name", "Marks", "Gender", "DOB",
"Address"]
table_data = [list(record)]

print(tabulate(table_data, headers=headers,
tablefmt="pretty"))
else:
print("Record not found")

choice = input("Do you want to search for another record (y/n)?


").lower()
if choice != 'y':
break

def view_all_records(connection):
while True:
print("List of All Records (Tabulated Format)")
print("===================")

select_all_query = "SELECT * FROM students"

cursor = [Link]()
[Link](select_all_query)

records = [Link]()

headers = ["Rollno", "Name", "Marks", "Gender", "DOB", "Address"]


table_data = []

for record in records:


table_data.append(list(record))

print(tabulate(table_data, headers=headers, tablefmt="pretty"))

choice = input("Do you want to view all records again (y/n)?


").lower()
if choice != 'y':
break

def sort_records_menu(connection):
while True:
print("\nSort Records")
print("============")
print("1. Sort by Rollno")
print("2. Sort by Name")
print("3. Sort by Marks")
print("4. Sort by Gender")
print("5. Sort by DOB")
print("6. Sort by Address")
print("7. Back to Main Menu")

choice = int(input("Enter your choice: "))

if choice == 1:
sort_records(connection, "rollno")
elif choice == 2:
sort_records(connection, "name")
elif choice == 3:
sort_records(connection, "marks")
elif choice == 4:
sort_records(connection, "gender")
elif choice == 5:
sort_records(connection, "dob")
elif choice == 6:
sort_records(connection, "address")
elif choice == 7:
break
else:
print("Invalid choice. Please try again.")

def sort_records(connection, column):


cursor = [Link]()
select_all_query = f"SELECT * FROM students ORDER BY {column}"

[Link](select_all_query)

records = [Link]()

headers = ["Rollno", "Name", "Marks", "Gender", "DOB", "Address"]


table_data = []

for record in records:


table_data.append(list(record))
print(f"\nRecords Sorted by {[Link]()} (Tabulated
Format)")
print("===================")
print(tabulate(table_data, headers=headers, tablefmt="pretty"))

def filter_records_menu(connection):
while True:
print("\nFilter Records")
print("==============")
print("1. Filter by Marks (Greater than)")
print("2. Filter by Marks (Less than)")
print("3. Filter by Gender (Male)")
print("4. Filter by Gender (Female)")
print("5. Back to Main Menu")

choice = int(input("Enter your choice: "))

if choice == 1:
filter_records(connection, "marks", ">")
elif choice == 2:
filter_records(connection, "marks", "<")
elif choice == 3:
filter_records(connection, "gender", "=", "Male")
elif choice == 4:
filter_records(connection, "gender", "=", "Female")
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")

def filter_records(connection, column, operator, value=None):


if column == "gender":
select_all_query = f"SELECT * FROM students WHERE {column}
{operator} %s"
data = (value,)
elif column == "marks":
value = float(input(f"Enter value to filter {column} {operator}:
"))
select_all_query = f"SELECT * FROM students WHERE {column}
{operator} %s"
data = (value,)
else:
print("Invalid column for filtering.")
return

cursor = [Link]()
[Link](select_all_query, data)

records = [Link]()

headers = ["Rollno", "Name", "Marks", "Gender", "DOB", "Address"]


table_data = []

for record in records:


table_data.append(list(record))

print(f"\nRecords Filtered by {column} {operator} {value} (Tabulated


Format)")
print("===================")
print(tabulate(table_data, headers=headers, tablefmt="pretty"))

def export_to_csv(connection):
while True:
print("Export Records to CSV")
print("=====================")
file_name = input("Enter the CSV file name (without extension):
")

select_all_query = "SELECT * FROM students"


cursor = [Link]()
[Link](select_all_query)

records = [Link]()

headers = ["Rollno", "Name", "Marks", "Gender", "DOB", "Address"]


file_path = f"{file_name}.csv"

with open(file_path, mode='w', newline='') as file:


writer = [Link](file)
[Link](headers)
[Link](records)

print(f"Records exported to {file_path}")

choice = input("Do you want to export more records (y/n)?


").lower()
if choice != 'y':
break

if __name__ == "__main__":
# Connect to the MySQL server
db_connection = create_connection()

# Create the "studentrec" database if it doesn't exist


create_database(db_connection.cursor(), "studentrec")

# Use the "studentrec" database


db_connection.database = "studentrec"

# Create the students table if it doesn't exist


create_table(db_connection)

choice = 0
while choice != 11:
print("\n=================================================")
print("------------------<<Main Menu>>------------------")
print("=================================================\n")
print("1. Add a new Record")
print("2. Modify Existing Record")
print("3. Delete Existing Record")
print("4. Search a Record (Tabulated Format)")
print("5. List all Records (Tabulated Format)")
print("6. Sort Records")
print("7. Filter Records")
print("8. Export Records to CSV")
print("9. Show Databases and Tables")
print("0. Exit")
choice = int(input('\nEnter your choice : '))

if choice == 1:
add_record(db_connection)
elif choice == 2:
modify_record(db_connection)
elif choice == 3:
delete_record(db_connection)
elif choice == 4:
search_record(db_connection)
elif choice == 5:
view_all_records(db_connection)
elif choice == 6:
sort_records_menu(db_connection)
elif choice == 7:
filter_records_menu(db_connection)
elif choice == 8:
export_to_csv(db_connection)
elif choice == 9:
show_databases_and_tables(db_connection)
elif choice == 0:
print("\n==================================================")
print("---------<<Program Terminated. Goodbye!>>---------")
print("==================================================\n")
break
Output

1. Main Menu:
2. Add a New Record :

3. Modify Existing Record :


4. Delete Existing Record :

5. Search a Record :
6. List All Records :

7. Sort Records :
8. Sql Representation :

You might also like