Practicals SQL Notes
Practicals SQL Notes
import pymysql
# Create connection and cursor
con = pymysql.connect(host="localhost", user="root", password="a!b@c#d$e%f67890")
mycursor = con.cursor()
def ins_rec():
mycursor.execute("create database if not exists students;")
mycursor.execute("use students")
mycursor.execute("CREATE TABLE IF NOT EXISTS EMP(Eno int, Ename varchar(30), Dept char(25), DOJ date,
Salary int)")
# Take user inputs
no = input("Enter Employee No.:")
name = input("Enter Employee Name:")
de = input("Enter Employee Department:")
doj = input("Enter Date of Joining:")
sal = input("Enter Employee Salary:")
# Insert record
query = "insert into emp values (%s, %s, %s, %s, %s)"
mycursor.execute(query, (no, name, de, doj, sal))
# Fetch and display all records
mycursor.execute("select * from emp;")
c = mycursor.fetchall()
for i in c:
print(i)
con.commit()
def search_rec():
x = int(input("Enter Employee ID:"))
mycursor.execute("use students")
# Fetch the record based on Employee No.
mycursor.execute("select * from emp where eno=%s", (x,))
cd = mycursor.fetchone()
print(cd)
con.commit()
def more_cons():
mycursor.execute("use students")
# Input department and check for salary > 50,000
d = input("Enter Department:")
mycursor.execute("select * from emp where salary > 50000 and dept=%s", (d,))
cd = mycursor.fetchall()
for i in cd:
print(i)
con.commit()
# Main loop
while True:
print("1-Insert record in table")
print("2-Search record using Employee Number")
print("3-Search record using Department and Salary greater than 50000")
print("4-Terminate")
o = int(input("Enter Choice:"))
if o == 1:
ins_rec()
elif o == 2:
search_rec()
elif o == 3:
more_cons()
else:
print("Terminated")
break
# Close connection after exiting the loop
con.close()