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

Lab 1

The document provides a comprehensive guide on creating and managing a database named 'dbbpa6' using SQL, including CRUD operations, altering tables, and using various SQL clauses like JOIN, GROUP BY, and HAVING. It also includes Python scripts for connecting to the database, creating tables, inserting data, and parsing different data formats such as JSON, XML, and CSV. Additionally, it covers creating views and performing operations on them.

Uploaded by

Hack the Box
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)
4 views

Lab 1

The document provides a comprehensive guide on creating and managing a database named 'dbbpa6' using SQL, including CRUD operations, altering tables, and using various SQL clauses like JOIN, GROUP BY, and HAVING. It also includes Python scripts for connecting to the database, creating tables, inserting data, and parsing different data formats such as JSON, XML, and CSV. Additionally, it covers creating views and performing operations on them.

Uploaded by

Hack the Box
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
You are on page 1/ 28

Lab 1: Create database name dbbpa6

Query:
Create database dbbpa6;
Lab 2: CRUD Operation
Create Operation:
# Create table student with necessary columns and constraints
Query:
create table student (
id int primary key,
name varchar(50),
faculty varchar(20),
age int,
address varchar(50)
);

Insert Operation:
# Insert data in to student table
Query:
insert into student (id, name, faculty, age, address) values
(1, 'Hari Thapa', 'BBS', 21, 'Dang'),
(2, 'Ankit Neupane', 'BBS', 21, 'Dang'),
(3, 'Ram Thapa', 'BPA', 21, 'Dang'),
(4, 'Sita KC', 'BPA', 20, 'NPJ'),
(5, 'Krishna', 'BPA', 19, 'Rolpa'),
(6, 'Suresh', 'BBA', 21, 'Butwal');
Read Operation:
# Display all the data of the table student
Query:
select * from student;
Result:

# Display information of all student whose age is less than 20


Query:
select * from student where age<20;
Result:

# Display information of all student whose age is greater than 20


Query:
select * from student where age>20;
Result:

# Display information of all student whose age is greater than or equals to 20


Query:
select * from student where age>=20;
Result:
# Display information of all student whose age is less than or equals to 20
Query:
select * from student where age<=20;
Result:

# Display information of all student who is from NPJ


Query:
select * from student where address = 'NPJ';
Result:

# Display information of all student who is studding in BPA


Query:
select * from student where faculty = 'BPA';
Result:

# Display name, faculty and address of student who is from out of NPJ
Query:
select name, faculty, address from student where address != 'NPJ';
Result:

# Display name, age and faculty of student whose age is greater than 20 and
studies in BPA
Query:
select name, age, faculty from student where age>20 and faculty = 'BPA';
Result:

# Display name, faculty and address of student who is studding in BPA or lives
in NPJ
Query:
select name, faculty, address from student where faculty = 'BPA' or address =
'NPJ';
Result:

Delete Operation:
# Display information of student table
Query:
select* from student;
Result:
# Delete the data from student whose id is 3
Query:
delete from student where id = 3;
# Display information of student table
Query:
select* from student;
Result:

Here the data of student whose id is 3 is deleted. So it is not in current table.

Update Operation:
# Change the faculty of student as BBA whose id is 2
Query:
update student set faculty = 'BBA' where id = 2;
Result:
# Change the age as 25 and address as Npj whose id is 6
Query:
update student set age = 25, address = 'Npj' where id = 6;
Result:

Lab 3: Alter Commands


#Add column to existing table
Query:
alter table student add gender varchar(10);
select* from student;
Result:

# Rename column gender to sex for MySQL database


Query:
alter table student change column gender sex varchar(6);
select* from student;
Result:

# Change datatype for MySQL database


Query:
alter table student modify sex char;
describe student;
Result:
# Add constraint not null to existing column sex
Query:
alter table student modify sex char not null;
describe student;
Result:

# delete not null constraint from column sex


Query:
alter table student modify sex char;
describe student;
Result:

# Drop/Delete column sex from table


Query:
alter table student drop column sex;
select* from student;
Result:
# Change the table student to tblstudent
Query:
alter table student rename tblstudent;
select* from tblstudent;
Result:

# Truncate/Delete all the rows from table


Query:
truncate table tblstudent;
select* from tblstudent;
Result:
Lab 4: Like Clauses
#Display information of student whose name is start with h
Query:
select* from student where name like 'h%';
Result:

#Display information of student whose name ends with a;


Query:
select* from student where name like '%a';
Result:

#Display information of student whose name contain th


Query:
select* from student where name like '%th%';
Result:

#Display information of student whose name start with any character followed
by uresh
Query:
select* from student where name like '_uresh';
Result:

#Display information of student whose name contain t followed by 4


characters
Query:
select* from student where name like '%t____';
Result:

Lab 5: Order by clause


#Display information of student table shorting by age in ascending order
Query:
select* from student order by age;
Result:

#Display information of student table shorting by age in descending order


Query:
select* from student order by age desc;
Result:

#Display information of student table shorting by name in ascending order


Query:
select* from student order by name;
Result:

# Display information of student table shorting by name in descending order


Query:
select* from student order by name desc;
Result:
#Display info shorting by age in ascending order if age is same then short by
address in ascending order
Query:
select* from student order by age, address;
Result:

Lab 6: Group by clause and alias


#Display the name and faculty as Student_Name and Program respectively
from student table
Query:
select name as Student_Name, faculty as Program from student;
Result:

#Display faculty and number of students study in corresponding faculties


Query:
select faculty as Program, count(id) as Students from student group by faculty;
Result:

#Display faculty and number of students study in corresponding faculties in


descending order
Query:
select faculty as Program, count(id) as Students from student group by
program order by count(id) desc;
Result:

Lab 7: Having Clause


#Display faculty and number of student which have more than 2 students
Query:
select faculty, count(id) as Tot_Std from student group by faculty having
count(id)>2;
Result:

#Display name, age and number of students having more than 2 students in an
age group
Query:
select name, age, count(id) as Tot_Std from student group by age having
count(id)>=2;
Result:

Lab 8: Distinct Clause


#Display the different age group from student table
Query:
select distinct age from student order by age;
Result:

#Display the total number of different age group


Query:
select count(distinct age) as total_age_group from student;
Result:

Lab 9: Between Clause


#Display information of student whose age is between 19 and 21
Query:
select* from student where age between 19 and 21;
Result:

#Display the information between name krishna and suresh and sort in
ascending order
Query:
select* from student where name between 'krishna' and 'Suresh' order by
name;
Result:

Lab 10: Join Relations


#Create two tables employees and departments with necessary constraints
Query:
create table employees(
empID int primary key,
empName varchar(50),
empPhone varchar(10),
depID int,
foreign key fk_dept (depID) references departments(depID)
);
Query:
create table departments(
depID int primary key,
DepName varchar(50)
);
# Insert data into employees and departments tables
Query:
insert into employees(empId, empName, empPhone, depID) values
(1, 'Ram Karki', '9851234567',1),
(2, 'Sudan Karki', '9851276567',2),
(3, 'Ramila Chand', '9851237867',1),
(4, 'Asmita KC', '9851234267',1),
(5, 'Lautan Tharu', '9851290567',2),
(6, 'Prakash Gupta', '9851200567',3),
(7, 'Radhika Sonari', '9851214567',6),
(8, 'Binisha Thapa', '9851714567',3),
(9, 'Sharmila Shahi', '9851114567',5),
(10, 'Narendra Shahi', '9800234567',1);
Query:
insert into departments(depID, depName) values
(1, 'HR'),
(2, 'Account'),
(3, 'Hardware'),
(4, 'Software Development'),
(5, 'Administration'),
(6, 'Out Reach');

Inner Join:
#Display name and department of employee who is work in HR department
Query:
select empName, depName from employees
inner join departments
on employees.depID = departments.depID
where departments.depName='hr';
Result:
#Display the information of all employees with their corresponding
department name
Query:
select* from employees
inner join departments
on employees.depID = departments.depID;
Result:

Left Join:
# display the information of all employees with their corresponding
department name
Query:
select* from employees
left join departments
on employees.depID = departments.depID;

Result:
Right Join:
# display the information of all employees with their corresponding
department name
Query:
select* from employees
right join departments
on employees.depID = departments.depID;
Result:

Lab 11: Creating View


# Create a view of student who are studying in BPA
Query:
create view bpastudents as
select * from student where faculty = 'BPA';
# Display information of bpastudents view
Query:
select * from bpastudents;
Result:

# Display information of students whose address is NPJ


Query:
select* from bpastudents where address='npj';
Result:

# Insert data into view bpastudents


Query:
insert into bpastudents(id, name, faculty, age, address)
values (7,'Kumar Sanu', 'BPA', 25, 'NPJ');

# Display information
Query:
select * from bpastudents;
Result:

# update age as 26 whose id is 78


Query:
update bpastudents set age=26 where id=7;
select * from bpastudents;
Result:

# Delete data of student whose id is 5


Query:
delete from bpastudents where id = 5;
select * from bpastudents;
Result:

Lab 12: CRUD Operation using Python


Connect to Server:
File Name: connection.py
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", password="")
if(con):
print("Connected to Server.")
else:
print("Connection Fail.")

Create Database:
File Name: create_db.py
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", password="")
mycursor = con.cursor()
try:
mycursor.execute("create database db_MMC")
print("Database Created Successfully..")
con.close()
except:
con.rollback()
con.close()

Create Table:
File Name: create_table.py
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", password="",
database="db_MMC")
mycursor = con.cursor()
try:
mycursor.execute("create table student(Sid int primary key, Sname
varchar(50), Sgender varchar(6), Sage int, Sfee double)")
print("Table created successfully..")
con.close()
except:
con.rollback()
con.close()

Insert Data into Table:


File Name: insert_data.py
import mysql.connector
con= mysql.connector.connect(host="localhost", user="root", password="",
database="db_MMC")
mycursor = con.cursor()
try:
mycursor.execute("insert into student(Sid,Sname,Sgender,Sage,Sfee)
values(7,'Rahul KC','Male',20,500)")
con.commit()
print("Data inserted successfully..")
con.close()
except:
con.rollback()
con.close()

# For insert multiple data together


insertdata = "insert into student(Sid,Sname,Sgender,Sage,Sfee) values(%s,%s,
%s,%s,%s)"
mydata = [
(2,'Ramesh Shah','Male',25,40000),
(3,'Sunita Rana','Female',23,60000),
(4,'Kumar Sanu','Male',25,40000),
(5,'Saraswati Bista','Female',25,70000),
(6,'Basanti Rimal','Female',20,35000)
]
mycursor.executemany(insertdata,mydata)

Display Data:
File Name: display_data.py
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", password="",
database="db_MMC")
mycursor = con.cursor()
mycursor.execute("select * from student")
showResult = mycursor.fetchall()
print("ID Name Gender Age Fee")
for i in showResult:
id = i[0]
name = i[1]
gender = i[2]
age = i[3]
fee = i[4]
print(id,name,gender,age,fee)
con.close()
Output:
ID Name Gender Age Fee
2 Mina KC Female 25 50001.0
3 Sunita Rana Female 23 500010.59
4 Kumar Sanu Male 25 10000.0
5 Saraswati Bista Female 25 10000.0
6 Basanti Rimal Female 20 10000.0
7 Rahul KC Male 20 500.0
Update Data:
File Name: update_data.py
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", password="",
database="db_MMC")
mycursor = con.cursor()
try:
mycursor.execute("update student set Sfee=500010.59 where Sid=3")
con.commit()
print("Data updated successfully")
con.close()
except:
con.rollback()
con.close()

Lab 13: Parsing JSON data


Parsingjson.py
import json
jsonobj = '{ "name":"John", "age":30, "city":"New York"}'
parsedata = json.loads(jsonobj)
print("Name: "+parsedata["name"])
print("City: "+parsedata["city"])
print("Age: "+str(parsedata["age"]))

Result:
Name: John
City: New York
Age: 30
Lab 14: Parsing Python dictionary to JSON data
Parsejson.py
import json
pyobj = {
"name": "John",
"age": 30,
"city": "New York"
}
jsondata = json.dumps(pyobj)
print(jsondata)
Result:
{"name": "John", "age": 30, "city": "New York"}

Lab 15: Parsing XML data


Parsexml.py
from xml.dom import minidom
xmldata = '''
<student roll="1" name="surya">
<sub1>5.56</sub1>
<sub2>6.0</sub2>
<sub3>5.5</sub3>
</student>
'''
parseddata = minidom.parseString(xmldata)
sub1 = float(parseddata.getElementsByTagName('sub1')
[0].firstChild.nodeValue)
sub2 = float(parseddata.getElementsByTagName('sub2')
[0].firstChild.nodeValue)
sub3 = float(parseddata.getElementsByTagName('sub3')
[0].firstChild.nodeValue)
avgmarks = (sub1+sub2+sub3)/3
print(f"Average Marks: {avgmarks:.2f}")

Result:
Average Marks: 5.69

Lab 16: Parsing CSV data


Parsecsv.py
import csv
csv_data = '''Name,Age,Location
Ram,30,Nepalgunj
Sita,25,Dang
Gopal,28,Rolpa
'''
reader = csv.reader(csv_data.splitlines())
next(reader)
for row in reader:
name, age, location = row
print(f"Name: {name}, Age: {age}, Location: {location}")

Result:
Name: Ram, Age: 30, Location: Nepalgunj
Name: Sita, Age: 25, Location: Dang
Name: Gopal, Age: 28, Location: Rolpa

THE END

You might also like