0% found this document useful (0 votes)
40 views9 pages

Employee and Student Data Management

The document contains multiple Python scripts that demonstrate various database operations using MySQL and data handling with files. It includes functions for creating and displaying employee records, student data, and sales records, as well as operations like inserting, querying, and updating data in a MySQL database. Additionally, it showcases the use of CSV and binary files for data storage and retrieval.

Uploaded by

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

Topics covered

  • Data Serialization,
  • Data Architecture,
  • Data Grouping,
  • Data Fetching,
  • Data Sorting,
  • Conditional Queries,
  • Sales Records,
  • CSV Handling,
  • Data Management,
  • User Input
0% found this document useful (0 votes)
40 views9 pages

Employee and Student Data Management

The document contains multiple Python scripts that demonstrate various database operations using MySQL and data handling with files. It includes functions for creating and displaying employee records, student data, and sales records, as well as operations like inserting, querying, and updating data in a MySQL database. Additionally, it showcases the use of CSV and binary files for data storage and retrieval.

Uploaded by

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

Topics covered

  • Data Serialization,
  • Data Architecture,
  • Data Grouping,
  • Data Fetching,
  • Data Sorting,
  • Conditional Queries,
  • Sales Records,
  • CSV Handling,
  • Data Management,
  • User Input

#1

import pickle

# Function to create the binary file [Link]


def CreateEmp():
x=int(input("enter number of records you want to enter:"))
file=open('[Link]', 'wb')
for i in range (x):
EID = int(input("Enter Employee ID: "))
Ename = str(input("Enter Employee Name:"))
designation = input("Enter Designation: ")
salary = float(input("Enter Salary: "))
employee = {'EID': EID, 'Ename': Ename, 'designation': designation,
'salary': salary}
[Link](employee, file)

# Function to display employees with salary more than 50,000


def display():
file=open('[Link]', 'rb')
while True:
try:
employee = [Link](file)
if employee['salary'] > 50000:
print("EID",employee['EID'], "Name",employee['Ename'])
except EOFError:
break
CreateEmp()
display()
-----------------------------------------------------------------------------------
-----------
import [Link]

# Connect to MySQL server


con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()

# Create database and use it


[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')

# Create table
[Link]('''
CREATE TABLE IF NOT EXISTS EMPLOYEE (
Empid INT PRIMARY KEY,
EName VARCHAR(50),
CompName VARCHAR(50),
City VARCHAR(50),
SEX CHAR(1)
)
''')
print("Table Created")

# Clear previous records


[Link]('DELETE FROM EMPLOYEE')

# Insert records one by one


[Link]("INSERT INTO EMPLOYEE VALUES (11, 'Aleshia Rosenburg', 'Hawerby',
'Hawerby', 'F')")
[Link]("INSERT INTO EMPLOYEE VALUES (22, 'Evan Gemini', 'Abbey Ward',
'Abbey Ward', 'M')")
[Link]("INSERT INTO EMPLOYEE VALUES (33, 'Franci Elliott', 'Southbourne',
'Southbourne', 'F')")
[Link]("INSERT INTO EMPLOYEE VALUES (44, 'Ulysses Mcmahan', 'Hawerby',
'Hawerby', 'M')")
[Link]("INSERT INTO EMPLOYEE VALUES (55, 'Tyisha Champagne', 'Hawerby',
'Hawerby', 'F')")

[Link]()
print('Records Inserted')

# Query a: Display employee data for female gender


[Link]('SELECT * FROM EMPLOYEE WHERE SEX = "F"')
x=[Link]()
for emp in x:
print(emp)

# Query b: Display name and city of employees whose Empid is 30 and above
[Link]('SELECT EName, City FROM EMPLOYEE WHERE Empid >= 30')
y=[Link]():
for emp in y:
print(emp)

# Close connection
[Link]()
-----------------------------------------------------------------------------------
------------------------------------------
2

def count_lines():
count = 0
file=([Link], 'r')
x=[Link]()
for i in x:
if i[0]=='A'or'E'or'I':
count += 1
print("Number of lines starting with A, E, or I: ",count)
count_lines()

-----------------------------------------------------------------------------------
--------------------------------------

import [Link]

# Connect to MySQL server


con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()

# Create database and use it


[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')

# Table creation
[Link]('''
CREATE TABLE IF NOT EXISTS SALES (
SalesId INT PRIMARY KEY,
Salesperson VARCHAR(50),
Item VARCHAR(50),
Units INT,
UnitCost INT,
Totalcost INT
)
''')
print("table is created")
# Clear previous records for simplicity
[Link]('DELETE FROM SALES')

# Record insertion
[Link]("INSERT INTO SALES VALUES (100, 'Jones', 'Pen', 45, 10, 450)")
[Link]("INSERT INTO SALES VALUES (102, 'Kivell', 'Binder', 50, 19, 950)")
[Link]("INSERT INTO SALES VALUES (105, 'Jardine', 'Pencil', 36, 16,
576)")
[Link]("INSERT INTO SALES VALUES (106, 'Gill', 'Pen', 27, 19, 513)")
[Link]("INSERT INTO SALES VALUES (115, 'Andrews', 'Pen', 75, 10, 750)")
[Link]("INSERT INTO SALES VALUES (119, 'Jardine', 'Pencil', 90, 11,
990)")

# Commit changes
[Link]()
print([Link], 'Records Inserted')

# Query a: Search records for item 'Pen' with Totalcost more than 600
[Link]("SELECT * FROM SALES WHERE Item = 'Pen' AND Totalcost > 600")
x=[Link]()
for record in x:
print(record)

# Query b: List items with UnitCost more than 15, sorted by Units

[Link]("SELECT * FROM SALES WHERE UnitCost > 15 ORDER BY Units")


y=[Link]()
for record in y:
print(record)

# Close the connection


[Link]()
-----------------------------------------------------------------------------------
--------------------------

import csv

# Function to get student details and write data to CSV file


def get_and_write_student_data():
more_records = 'y'
while more_records.lower() == 'y':
roll_number = input("Enter roll number: ")
name = input("Enter student name: ")
marks = input("Enter marks: ")

student_data = [roll_number, name, marks]

# Writing to CSV file in 'w' mode (overwrite the file each time)
file = open('[Link]', mode='a', newline='') # Changed to 'a' for
appending new records
writer = [Link](file)
[Link](student_data)
[Link]()

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

# Function to read and display data from CSV file


def display_csv():
try:
file = open('[Link]', mode='r')
reader = [Link](file)
print("\nContents of '[Link]':")
for row in reader:
print(row)
[Link]()
except FileNotFoundError:
print("File not found. No data to display.")

# Get student details and write to CSV


get_and_write_student_data()

# Display contents of CSV file


display_csv()
-----------------------------------------------------------------------------------
------------------------

import [Link]

# Establishing the connection


con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()

# Create the PRACTICAL database if it doesn't exist


[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')

# Table creation: Creating the STUDENT table


[Link]('''
CREATE TABLE IF NOT EXISTS STUDENT (
Id INT,
SName VARCHAR(50),
Gender VARCHAR(10),
Country VARCHAR(50),
Age INT,
Marks INT
)
''')

# Inserting records into the STUDENT table one by one


[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (1562, "Dulce", "Female", "United States", 32, 495)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (1582, "Mara", "Female", "Great Britain", 25, 426)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (2587, "Philip", "Male", "France", 36, 480)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (3549, "Kathleen", "Female", "United States", 25, 400)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (3598, "Etta", "Female", "Great Britain", 56, 325)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (6548, "Vinca", "Male", "United States", 40, 485)')

# Commit the transaction


[Link]()
print("6 Records Inserted")

# Query a. List the name of Male students sorted by highest to lowest marks
[Link]('''
SELECT SName FROM STUDENT
WHERE Gender = "Male"
ORDER BY Marks DESC
''')
male_students = [Link]()

print("\nMale Students sorted by marks (highest to lowest):")


for student in male_students:
print(student[0])

# Query b. Search minimum Marks from student table for United States
[Link]('''
SELECT MIN(Marks) FROM STUDENT
WHERE Country = "United States"
''')
min_marks_us = [Link]()
print("\nMinimum Marks for students from United States:", min_marks_us[0])

# Closing the connection


[Link]()

-----------------------------------------------------------------------------------
------------------------------------------------------------

import pickle

# Function to create the '[Link]' file and input student data


def CreateStd():
# Open file in binary write mode
file = open('[Link]', 'wb')
while True:
# Input student data
SID = int(input("Enter Student ID: "))
Sname = input("Enter Student Name: ")
Stream = input("Enter Stream: ")
Marks = float(input("Enter Marks: "))

# Create a dictionary to hold the student record


student_record = {'SID': SID, 'Sname': Sname, 'Stream': Stream, 'Marks':
Marks}

# Use pickle to serialize the student record and write it to the file
[Link](student_record, file)

# Ask user if they want to enter another record


more = input("Do you want to enter another student record? (y/n): ")
if [Link]() != 'y':
break

[Link]() # Closing the file after writing


print("Student records have been written to '[Link]'.")

# Function to display student records with marks greater than 350


def sdisplay():
# Open the file in binary read mode
file = open('[Link]', 'rb')
print("\nStudents with marks greater than 350:")
while True:
try:
# Use pickle to deserialize the student record
student_record = [Link](file)

# Check if marks are greater than 350 and display the record
if student_record['Marks'] > 350:
print(f"ID: {student_record['SID']}, Name:
{student_record['Sname']}, Stream: {student_record['Stream']}, Marks:
{student_record['Marks']}")
except EOFError:
break

[Link]() # Closing the file after reading

# Main execution
# Create student records in the binary file
CreateStd()

# Display students with marks greater than 350


sdisplay()
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------
import [Link]

# Establishing the connection to MySQL


con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()

# Create the PRACTICAL database if it doesn't exist


[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')

# Table creation (BOOKS)


[Link]('''
CREATE TABLE IF NOT EXISTS BOOKS (
BOOK_NAME VARCHAR(100),
PUBLISHERS VARCHAR(100),
PRICE INT
)
''')

# Inserting records into the BOOKS table


[Link]('''INSERT INTO BOOKS (BOOK_NAME, PUBLISHERS, PRICE)
VALUES
('FAST COOK', 'EPB', 355),
('THE TEARS', 'TDH', 650),
('MY FIRST C++', 'EPB', 350),
('C++ BRAINWORKS', 'TDH', 350),
('THUNDERBOLTS', 'FIRST PUBL', 750)''')

# Commit the changes to the database


[Link]()
print([Link], 'Records Inserted')

# a. Query to increase the price of all books published by TDH by 100


[Link]('''
UPDATE BOOKS
SET PRICE = PRICE + 100
WHERE PUBLISHERS = 'TDH'
''')
[Link]()
print("Price updated for all books of TDH publishers by 100.")

# b. Query to display all books sorted by name in Z to A order


[Link]('''
SELECT BOOK_NAME, PUBLISHERS, PRICE
FROM BOOKS
ORDER BY BOOK_NAME DESC
''')
books = [Link]()

print("\nBooks sorted by name (Z to A):")


for book in books:
print(book)

# Close the connection


[Link]()

-----------------------------------------------------------------------------
5
# Function to create a list of 10 elements and push numbers greater than 50 into a
stack
def create_and_push_to_stack():
# Creating a list with 10 elements (random numbers for example purposes)
numbers = [12, 75, 44, 56, 85, 22, 91, 37, 62, 50]
stack = [] # Empty stack
for num in numbers:
if num > 50:
[Link](num)
return stack

# Function to pop and display the content of the stack


def pop_and_display_stack(stack):
if stack==[]: # If the stack is empty
print("Stack is empty")
else:
print("Popping elements from the stack:")
element = [Link]()
print("poped item",element)
print("stack is")
top=len(stack)-1
for i in range(top-1,-1,-1):
print(i)

-----------------------------------------------------------------------------------
---------------------------------
import [Link]

# Establish the connection to MySQL


con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()

# Create the PRACTICAL database if it doesn't exist


[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')

# Table creation: STUDENT


[Link]('''
CREATE TABLE IF NOT EXISTS STUDENT (
Name VARCHAR(100),
AvgMark FLOAT,
Grade CHAR(1),
Class VARCHAR(10)
)
''')

# Inserting records into the STUDENT table


[Link]('''INSERT INTO STUDENT (Name, AvgMark, Grade, Class)
VALUES
('Karan', 78.5, 'B', '12B'),
('Divakar', 89.2, 'A', '11C'),
('Divya', 68.6, 'C', '12C'),
('Arun', 73.1, 'B', '12C'),
('Sabina', 90.6, 'A', '11A')''')

# Commit the changes to the database


[Link]()
print([Link], 'Records Inserted')

# a. List the names of students who are in class 12, sorted by average marks
[Link]('''
SELECT Name
FROM STUDENT
WHERE Class LIKE '12%'
ORDER BY AvgMark DESC
''')

# Fetching the result and displaying the names


print("\nList of students in class 12 sorted by average marks:")
students_12th = [Link]()
for student in students_12th:
print(student)

# b. Delete all the records whose AvgMark is less than 80


[Link]('''
DELETE FROM STUDENT
WHERE AvgMark < 80
''')

# Commit the deletion


[Link]()

# Closing the connection


[Link]()

Common questions

Powered by AI

Setting up a MySQL database involves defining and creating databases and tables before inserting records and executing queries. The process typically begins with connecting to a MySQL server and creating a database using SQL commands like `CREATE DATABASE IF NOT EXISTS PRACTICAL`. Following this, tables are created using statements such as `CREATE TABLE IF NOT EXISTS EMPLOYEE`, ensuring tables are defined with the necessary columns and data types. These steps ensure data is stored in structured formats, maintain data integrity through constraints like primary keys, and allow for efficient querying and data organization .

SQL queries can be crafted to retrieve data based on specific conditions such as gender and employee ID. For instance, to find employee data for females, the query `SELECT * FROM EMPLOYEE WHERE SEX = "F"` can be executed, which returns all records where the SEX field is 'F'. Another query, `SELECT EName, City FROM EMPLOYEE WHERE Empid >= 30`, filters records with an employee ID greater than or equal to 30, retrieving only the name and city columns of these records. These approaches allow targeted data retrieval with specific constraints .

CSV file manipulation allows for structured storage and easy retrieval of student records by writing each record as a row of comma-separated values, which can be read back to restore the data. Using Python's CSV module, the function get_and_write_student_data writes records sequentially, whereas display_csv reads and displays these records. A common issue that might arise is the FileNotFoundError during reading if the file hasn't been created yet, which means addressing file path or existence errors is crucial .

Using Python's pickle module for file operations allows for efficient storage and retrieval of student data in binary format, preserving data integrity and structure. The CreateStd function serializes records, storing them with fields like student ID, name, stream, and marks, while the sdisplay function deserializes them, filtering based on conditions such as marks exceeding 350. This approach offers advantages in handling complex data structures and maintaining data consistency. However, challenges include ensuring proper file handling to avoid data corruption and ensuring compatibility with Python's pickle format across different versions .

Python can automate data operations like counting lines in text files using functions, loops, and conditionals. The script defines a function to read lines from a file and increments a counter for each line starting with specified letters ('A', 'E', 'I'), showcasing basic text processing capabilities. Challenges include ensuring the file reading mode is correct to prevent errors and handling exceptions like incorrect file paths or empty files, which would lead to inaccurate counts or program crashes .

MySQL operations can manipulate book pricing through updates and condition-based queries, facilitating dynamic inventory management. For instance, increasing book prices for TDH publishers by executing `UPDATE BOOKS SET PRICE = PRICE + 100 WHERE PUBLISHERS = 'TDH'` allows publishers to adjust prices swiftly in response to market conditions or cost increases. The approach benefits publishers by maintaining competitive pricing strategies and improves inventory management by keeping pricing data current, aiding financial planning and stock valuation .

SQL can efficiently manage sales data by allowing filtering and sorting operations based on financial metrics. For instance, to find sales records for an item with a total cost exceeding a specific threshold, a query like `SELECT * FROM SALES WHERE Item = 'Pen' AND Totalcost > 600` can be employed, thus filtering records with a high total cost. For sorting items by unit cost, another query `SELECT * FROM SALES WHERE UnitCost > 15 ORDER BY Units` can order results by the number of units sold, helping prioritize or assess sales performance .

Querying SQL databases to manage student academic records is significant as it allows targeted data retrieval and analysis. For instance, retrieving names of students in a particular class, such as Class 12, sorted by average marks, helps in recognizing top performances, achieved through `SELECT Name FROM STUDENT WHERE Class LIKE '12%' ORDER BY AvgMark DESC`. This query sorts students based on their average marks, facilitating identification of academic strengths and weaknesses within the dataset. Additionally, deleting records with specific criteria, such as `DELETE FROM STUDENT WHERE AvgMark < 80`, helps maintain focus on stronger performances .

Structuring data in a stack is beneficial for operations like LIFO (Last In, First Out), making it ideal for backtracking and handling nested operations. In Python, numbers can be conditionally pushed onto a stack by iterating through a list and appending numbers that meet certain criteria (e.g., greater than 50). The function `create_and_push_to_stack()` demonstrates this by iterating over a list, pushing numbers to a stack for those exceeding 50. This approach eases managing specific subsets of data temporarily and efficiently, essential for recursive algorithms and managing execution contexts .

The Python pickle module can be used to serialize and deserialize data objects to a binary file, which allows for efficient storage and retrieval of complex data structures like dictionaries. In the context of employee data, you can use pickle to store records consisting of fields such as employee ID, name, designation, and salary. The CreateEmp function writes these records to a file in binary format. For analysis, such as displaying employees earning more than a specified amount, the display function deserializes the data to check conditions on specific fields like 'salary' .

You might also like