0% found this document useful (0 votes)
2 views

comp progs

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
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

comp progs

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
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

#1

import pickle

# Function to create the binary file emp.dat


def CreateEmp():
x=int(input("enter number of records you want to enter:"))
file=open('emp.dat', '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}
pickle.dump(employee, file)

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


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

# Connect to MySQL server


con = mysql.connector.connect(host="localhost", user="root", password="")
mycursor = con.cursor()

# Create database and use it


mycursor.execute('CREATE DATABASE IF NOT EXISTS PRACTICAL')
mycursor.execute('USE PRACTICAL')

# Create table
mycursor.execute('''
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


mycursor.execute('DELETE FROM EMPLOYEE')

# Insert records one by one


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

con.commit()
print('Records Inserted')

# Query a: Display employee data for female gender


mycursor.execute('SELECT * FROM EMPLOYEE WHERE SEX = "F"')
x=mycursor.fetchall()
for emp in x:
print(emp)

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

# Close connection
con.close()
-----------------------------------------------------------------------------------
------------------------------------------
2

def count_lines():
count = 0
file=(student.txt, 'r')
x=file.readlines()
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 mysql.connector

# Connect to MySQL server


con = mysql.connector.connect(host="localhost", user="root", password="")
mycursor = con.cursor()

# Create database and use it


mycursor.execute('CREATE DATABASE IF NOT EXISTS PRACTICAL')
mycursor.execute('USE PRACTICAL')

# Table creation
mycursor.execute('''
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
mycursor.execute('DELETE FROM SALES')

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

# Commit changes
con.commit()
print(mycursor.rowcount, 'Records Inserted')

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

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

mycursor.execute("SELECT * FROM SALES WHERE UnitCost > 15 ORDER BY Units")


y=mycursor.fetchall()
for record in y:
print(record)

# Close the connection


con.close()
-----------------------------------------------------------------------------------
--------------------------

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('marks.csv', mode='a', newline='') # Changed to 'a' for
appending new records
writer = csv.writer(file)
writer.writerow(student_data)
file.close()

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('marks.csv', mode='r')
reader = csv.reader(file)
print("\nContents of 'marks.csv':")
for row in reader:
print(row)
file.close()
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 mysql.connector

# Establishing the connection


con = mysql.connector.connect(host="localhost", user="root", password="")
mycursor = con.cursor()

# Create the PRACTICAL database if it doesn't exist


mycursor.execute('CREATE DATABASE IF NOT EXISTS PRACTICAL')
mycursor.execute('USE PRACTICAL')

# Table creation: Creating the STUDENT table


mycursor.execute('''
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


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

# Commit the transaction


con.commit()
print("6 Records Inserted")

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

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
mycursor.execute('''
SELECT MIN(Marks) FROM STUDENT
WHERE Country = "United States"
''')
min_marks_us = mycursor.fetchone()
print("\nMinimum Marks for students from United States:", min_marks_us[0])

# Closing the connection


con.close()

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

import pickle

# Function to create the 'std.dat' file and input student data


def CreateStd():
# Open file in binary write mode
file = open('std.dat', '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
pickle.dump(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 more.lower() != 'y':
break

file.close() # Closing the file after writing


print("Student records have been written to 'std.dat'.")

# Function to display student records with marks greater than 350


def sdisplay():
# Open the file in binary read mode
file = open('std.dat', 'rb')
print("\nStudents with marks greater than 350:")
while True:
try:
# Use pickle to deserialize the student record
student_record = pickle.load(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

file.close() # Closing the file after reading

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

# Display students with marks greater than 350


sdisplay()
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------
import mysql.connector

# Establishing the connection to MySQL


con = mysql.connector.connect(host="localhost", user="root", password="")
mycursor = con.cursor()

# Create the PRACTICAL database if it doesn't exist


mycursor.execute('CREATE DATABASE IF NOT EXISTS PRACTICAL')
mycursor.execute('USE PRACTICAL')

# Table creation (BOOKS)


mycursor.execute('''
CREATE TABLE IF NOT EXISTS BOOKS (
BOOK_NAME VARCHAR(100),
PUBLISHERS VARCHAR(100),
PRICE INT
)
''')

# Inserting records into the BOOKS table


mycursor.execute('''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


con.commit()
print(mycursor.rowcount, 'Records Inserted')

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


mycursor.execute('''
UPDATE BOOKS
SET PRICE = PRICE + 100
WHERE PUBLISHERS = 'TDH'
''')
con.commit()
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


mycursor.execute('''
SELECT BOOK_NAME, PUBLISHERS, PRICE
FROM BOOKS
ORDER BY BOOK_NAME DESC
''')
books = mycursor.fetchall()

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


for book in books:
print(book)

# Close the connection


con.close()

-----------------------------------------------------------------------------
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:
stack.append(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 = stack.pop()
print("poped item",element)
print("stack is")
top=len(stack)-1
for i in range(top-1,-1,-1):
print(i)

-----------------------------------------------------------------------------------
---------------------------------
import mysql.connector

# Establish the connection to MySQL


con = mysql.connector.connect(host="localhost", user="root", password="")
mycursor = con.cursor()

# Create the PRACTICAL database if it doesn't exist


mycursor.execute('CREATE DATABASE IF NOT EXISTS PRACTICAL')
mycursor.execute('USE PRACTICAL')

# Table creation: STUDENT


mycursor.execute('''
CREATE TABLE IF NOT EXISTS STUDENT (
Name VARCHAR(100),
AvgMark FLOAT,
Grade CHAR(1),
Class VARCHAR(10)
)
''')

# Inserting records into the STUDENT table


mycursor.execute('''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


con.commit()
print(mycursor.rowcount, 'Records Inserted')

# a. List the names of students who are in class 12, sorted by average marks
mycursor.execute('''
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 = mycursor.fetchall()
for student in students_12th:
print(student)

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


mycursor.execute('''
DELETE FROM STUDENT
WHERE AvgMark < 80
''')

# Commit the deletion


con.commit()

# Closing the connection


con.close()

You might also like