Create Database?
1. CREATE DATABASE sec_aids;
Open Database?
2. Use sec_aids;
Drop Database?
3. Drop database sec_aids;
To view all Databases in Mysql?
4. Show databases;
How to open Db?
5. ?
To create a new table?
6. CREATE TABLE users(id INT NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT
NULL, age INT NOT NULL,PRIMARY KEY(id));
To view all tables in a database?
7. Show tables;
To view structure of a table?
8. DESCRIBE users;
To insert a new column inside a table?
9. ALTER TABLE users ADD gender VARCHAR(10) NOT NULL AFTER AGE;
10. describe users;
To insert a multiple columns inside a table?
11. ALTER TABLE users ADD city VARCHAR(50) NOT NULL, ADD contact VARCHAR(50)
NOT NULL;
12. describe users;
To modify a column in a table?
13. ALTER TABLE users MODIFY contact VARCHAR(25) NOT NULL;
14. describe users;
To rename a table?
15. ALTER TABLE users RENAME TO students;
16. Show tables;
To view records in a Table?
17. SELECT * FROM students;
To insert a record into a table without mention column names?
18. INSERT INTO students VALUES(NULL,'Ram',25,'Male','Salem','9874563210');
19. Select *from students;
To insert multiple records into a table with mention column names?
20. INSERT INTO students(name,age,gender,city,contact) VALUES
('Ravi',23,'Male','Namakkal','9876543210'),('Sara',23,'Female','Erode','9874521360');
21. select *from students;
To delete a record from a table?
22. DELETE FROM students WHERE id=3;
23. Select *from students;
To modify/update a record in a Table?
24. UPDATE students SET city='Hosur',contact='9988776655' WHERE id=2;
25. select *from students;
To clear all data (or) records from a table?
26. TRUNCATE TABLE students;
SELECT- QUERIES
1. insert into students(name,age,gender,city,contact) values
('Agneeshwar',19,'m','Salem','9876543210'),
('Akash',22,'m','Namakkal','9876543210'),
('Arun',25,'m','Hosur','9876543210'),
('Ashok Kumar',20,'m','Salem','9876543210'),
('Asma Ahamed',18,'f','Namakkal','9876543210'),
('Harini',21,'f','Hosur','9876543210'),
('JayaShree',19,'f','Salem','9876543210'),
('Jessy',19,'f','Salem','9876543210'),
('Mohith',22,'m','Namakkal','9876543210'),
('Monesh Sai',24,'m','Hosur','9876543210'),
('Muthu Sri Sruthika',19,'f','Salem','9876543210'),
('Nithish',23,'m','Namakkal','9876543210'),
('Pratheesh',24,'m','Hosur','9876543210'),
('Ravi Varma',20,'m','Salem','9876543210'),
('Rithick',22,'m','Namakkal','9876543210'),
('Rithick Rosan',18,'m','Hosur','9876543210'),
('Roshini',21,'f','Salem','9876543210'),
('Sabari',23,'m','Namakkal','9876543210'),
('Sarnesh',21,'m','Hosur','9876543210'),
('Sibi Shree',22,'f','Salem','9876543210'),
('Supriya',19,'f','Namakkal','9876543210'),
('Tharika',21,'f','Hosur','9876543210'),
('valtina',20,'f','Salem','9876543210'),
('Yashwanth',23,'m','Hosur','9876543210');
2. select *from students;
Select particular fields in a table?
3. SELECT name,age FROM students;
Select records with criteria?
4. SELECT name,age,city FROM students WHERE city='Hosur';
Select records with multiple criteria’s?
5. SELECT name,age,city FROM students WHERE city='Hosur' AND age >= 23;
6. SELECT name,age,city FROM students WHERE city='Namakkal' OR city='Hosur';
7. SELECT name,age,city FROM students WHERE (city='Namakkal' OR city='Hosur') AND age >=
23;
To select unique values in a fields?
8. select city from students;
9. SELECT DISTINCT city FROM students;
To count unique values in a field?
10. SELECT COUNT(DISTINCT city) FROM students;
To count unique values in a field with allies name?
11. SELECT COUNT(DISTINCT city) AS Number_of_Cities FROM students;
To display N-Number of records while view all records in a table?
12. SELECT * FROM students LIMIT 5;
To Select a range of records ( ex: 5,7) here from 5th records to 7 no of records ?
13. SELECT * FROM students LIMIT 5,7;
To select the very first record from a table?
14. SELECT * FROM students LIMIT 0,1;
To select the very first record from a table?
15. SELECT * FROM students ORDER BY id DESC LIMIT 0,1;
To select maximum value in a table?
16. SELECT MAX(age) FROM students;
To select minimum value in a table?
17. SELECT MIN(age) FROM students;
To select average of a field?
18. SELECT AVG(age) FROM students;
To round a float value?
19. SELECT ROUND(AVG(age),0) FROM students;
To select sum of a field?
20. SELECT SUM(age) FROM students;
To count male and female records ?
21. select count(gender) from students;
To select group wise records?
22. SELECT gender,COUNT(gender) As Total FROM students GROUP BY gender;
WILD CARD QUERIES
To select values starts with some letters?
1. SELECT NAME FROM students WHERE name LIKE 'Ra%';
To select values ends with some letters?
2. SELECT NAME FROM students WHERE name LIKE '%ee';
To select values contains some letter?
3. SELECT NAME FROM students WHERE name LIKE '%hi%';
To select values having given keywords?
4. SELECT * FROM STUDENTS WHERE city IN('Salem','Namakkal');
To select values not having given keywords?
5. SELECT * FROM STUDENTS WHERE city NOT IN('Salem','Namakkal');
To select values using between keyword?
6. SELECT name, age FROM students WHERE age BETWEEN 24 AND 30;
1. use sec_aids;
2. create table attendance(AID int not null auto_increment,id int not null,ADATE date not
null,ASTATUS varchar(10) not null ,primary key(AID));
3. show tables;
4. insert into attendance(id,ADATE,ASTATUS)values
(1,'2019-11-01','p'),
(1,'2019-11-03','a'),
(1,'2019-11-03','a'),
(1,'2019-11-04','p'),
(2,'2019-11-01','a'),
(2,'2019-11-02','a'),
(2,'2019-11-03','a'),
(2,'2019-11-04','a'),
(3,'2019-11-01','p'),
(3,'2019-11-02','p'),
(3,'2019-11-03','p'),
(3,'2019-11-04','p'),
(4,'2019-11-01','p'),
(4,'2019-11-02','p'),
(4,'2019-11-03','a'),
(4,'2019-11-04','p'),
(5,'2019-11-01','p'),
(5,'2019-11-02','p'),
(5,'2019-11-03','p'),
(5,'2019-11-04','p'),
(6,'2019-11-01','p'),
(6,'2019-11-02','p'),
(6,'2019-11-03','p'),
(6,'2019-11-04','p'),
(7,'2019-11-01','p'),
(7,'2019-11-02','p'),
(7,'2019-11-03','p'),
(7,'2019-11-04','p'),
(8,'2019-11-01','p'),
(8,'2019-11-02','p'),
(8,'2019-11-03','a'),
(8,'2019-11-04','p'),
(9,'2019-11-01','p'),
(9,'2019-11-02','a'),
(9,'2019-11-03','a'),
(9,'2019-11-04','a'),
(10,'2019-11-01','p'),
(10,'2019-11-02','p'),
(10,'2019-11-03','p'),
(10,'2019-11-04','p'),
(11,'2019-11-01','p'),
(11,'2019-11-02','p'),
(11,'2019-11-03','p'),
(11,'2019-11-04','p'),
(12,'2019-11-01','p'),
(12,'2019-11-02','a'),
(12,'2019-11-03','a'),
(12,'2019-11-04','p'),
(13,'2019-11-01','p'),
(13,'2019-11-02','a'),
(13,'2019-11-03','p'),
(13,'2019-11-04','p'),
(14,'2019-11-01','p'),
(14,'2019-11-02','p'),
(14,'2019-11-03','p'),
(14,'2019-11-04','p'),
(15,'2019-11-01','p'),
(15,'2019-11-02','a'),
(15,'2019-11-03','p'),
(15,'2019-11-04','p'),
(16,'2019-11-01','p'),
(16,'2019-11-02','p'),
(16,'2019-11-03','p'),
(16,'2019-11-04','p'),
(17,'2019-11-01','p'),
(17,'2019-11-02','p'),
(17,'2019-11-03','p'),
(17,'2019-11-04','p'),
(18,'2019-11-01','p'),
(18,'2019-11-02','p'),
(18,'2019-11-03','p'),
(18,'2019-11-04','p'),
(19,'2019-11-01','a'),
(19,'2019-11-02','a'),
(19,'2019-11-03','a'),
(19,'2019-11-04','a'),
(20,'2019-11-01','p'),
(20,'2019-11-02','p'),
(20,'2019-11-03','p'),
(20,'2019-11-04','p'),
(21,'2019-11-01','p'),
(21,'2019-11-02','p'),
(21,'2019-11-03','p'),
(21,'2019-11-04','p'),
(22,'2019-11-01','p'),
(22,'2019-11-02','p'),
(22,'2019-11-03','a'),
(22,'2019-11-04','p'),
(23,'2019-11-01','p'),
(23,'2019-11-02','p'),
(23,'2019-11-03','p'),
(23,'2019-11-04','p'),
(24,'2019-11-01','p'),
(24,'2019-11-02','a'),
(24,'2019-11-03','a'),
(24,'2019-11-04','p');
5. select *from attendance;
6. select *from students;
7. select *from attendance where id=23;
Find total working days ?
8. select count(ADATE) As Tot_Working_Days from attendance;
9. select id,count(ADATE) As Tot_Working_Days from attendance group by id;
Find No of present and Absent Using decision making?
10. select id,count(ADATE) As Tot_Working_Days,count(if(ASTATUS='p',1,NULL)) As
Tot_Present,count(if(ASTATUS='a',1,NULL)) As Tot_Absent from attendance group by id;
JOINS
INNER JOIN
The INNER JOIN command returns
rows that have matching values in
both tables. Like intersection
LEFT JOIN
The LEFT JOIN command returns all
rows from the left table, and the
matching rows from the right table.
The result is NULL from the right side,
if there is no.
RIGHT JOIN
The RIGHT JOIN keyword returns all
records from the right table (table2),
and the matching records from the
left table (table1). The result is 0
records from the left side, if there is
no match.
1. create table emp(id integer unsigned not null auto_increment,name varchar(45) not null,des
varchar(45) not null ,doj date not null,primary key(id));
2. insert into emp(name,des,doj) values
('krish','manager','2019-09-10'),
('Moses','hr','2019-09-10'),
('Joyal','ACC','2019-09-11'),
('John','sales','2019-09-23'),
('daniel','sales','2019-10-02');
3. select *from emp;
4. create table salary(sid int not null auto_increment,id int not null,sdate date not null,amt int
not null,primary key(sid));
5. insert into salary(id,sdate,amt) values
(1,'2019-09-30',10000),
(2,'2019-09-30',7500),
(3,'2019-09-30',6000),
(4,'2019-09-30',4000);
In above able we have inserted details for 4-employees , the 5th employee DOJ is 2019-10-02 .. so
we can filtered it using some joins commands
6. select emp.name,emp.des,salary.sdate,salary.amt from emp inner join salary on
emp.id=salary.id;
While using joins we want to mention dot operator as prefix in each fields of the table like
( Ex: emp.name it means “name” – field from “emp” table )
“from emp” it means like “A”- table
“emp inner join salary” here salary like “B”- table , here “inner join” like intersection of
two sets( means it extract common records from both tables)
“on emp.id=salary.id” here we have check unique records based on “id” of both “emp”
and “Salary” tables.
Result:
Table-1: emp Table name: salary
Id Name Des DOJ Sid Id Sdate Amt
1 Krish Manager 2019-09-10 1 1 2019-09-30 10000
2 Moses HR 2019-09-10 2 2 2019-09-30 7500
3 Joyal ACC 2019-09-11 3 3 2019-09-30 6000
4 John Sales 2019-09-23 4 4 2019-09-30 4000
5 daneil sales 2019-10-02
Emp.id = salary.id
Id Id
1 1
2 2
3 3
4 4
RESULT
FIND “sep” month updated salary details (LEFT join)
7. select emp.id,emp.name,emp.des,salary.sdate,salary.amt from emp left join salary on
emp.id=salary.id;
RIGHT JOIN
8. select emp.id,emp.name,emp.des,salary.sdate,salary.amt from emp right join salary on
emp.id=salary.id;
in above right join result and inner join result both are giving same result , just you can update
another salary details in “Salary” table , then you can view the different result .
9. insert into salary(id,sdate,amt) values (6,'2019-09-01',7000);
10. select *from salary;
But 6th record not exists in “emp” – table now you can use “right join” then view the different result
11. select emp.id,emp.name,emp.des,salary.sdate,salary.amt from emp inner join salary on
emp.id=salary.id;
( it give same result )
12. select emp.id,emp.name,emp.des,salary.sdate,salary.amt from emp right join salary on
emp.id=salary.id;
now we got 5 records but 5th record displayed without name
13. select emp.id,emp.name,emp.des,salary.sdate,salary.amt from emp left join salary on
emp.id=salary.id;
Now we got 5th record without having Sdate and Amt because he joined on 2019-10-02
14. select *from students;
15. select *from attendance;
16. select students.name,attendance.ADATE,attendance.ASTATUS from students inner join
attendance on students.id=attendance.id;
Provide bus fair based on city ?
17. select distinct city from students;
18. select name,city from students;
19. select name,city,
CASE
WHEN city='Salem' THEN 100
END
as Bus_Fair from students;
20. select name,city,
CASE
WHEN city='Salem' THEN 100
WHEN city='Namakkal' THEN 150
WHEN city='Hosur' THEN 350
ELSE 0
END
as Bus_Fair from students;
21. select name,city,
CASE
WHEN city='Salem' THEN 100
WHEN city='Namakkal' THEN 150
WHEN city='Hosur' THEN 350
ELSE 0
END
as Bus_Fair from students WHERE city='Hosur';
22. update students set city='Madurai' where city='Salem';
23. select name,city,
CASE
WHEN city='Salem' THEN 100
WHEN city='Namakkal' THEN 150
WHEN city='Hosur' THEN 350
ELSE 0
END
as Bus_Fair from students;
ADVANCE QUERIES
1. SELECT *FROM STUDENTS;
2. ALTER TABLE STUDENTS ADD CID INT NOT NULL,ADD ROLLNO VARCHAR(20) NOT NULL;
3. UPDATE STUDENTS SET ROLLNO='2328K0109',CID=1 WHERE ID=1;
UPDATE STUDENTS SET ROLLNO='2328K0110',CID=2 WHERE ID=2;
UPDATE STUDENTS SET ROLLNO='2328K0111',CID=3 WHERE ID=3;
UPDATE STUDENTS SET ROLLNO='2328K0112',CID=1 WHERE ID=4;
UPDATE STUDENTS SET ROLLNO='2328K0113',CID=2 WHERE ID=5;
UPDATE STUDENTS SET ROLLNO='2328K0114',CID=3 WHERE ID=6;
UPDATE STUDENTS SET ROLLNO='2328K0115',CID=1 WHERE ID=7;
UPDATE STUDENTS SET ROLLNO='2328K0116',CID=2 WHERE ID=8;
UPDATE STUDENTS SET ROLLNO='2328K0117',CID=3 WHERE ID=9;
UPDATE STUDENTS SET ROLLNO='2328K0118',CID=1 WHERE ID=10;
UPDATE STUDENTS SET ROLLNO='2328K0119',CID=2 WHERE ID=11;
UPDATE STUDENTS SET ROLLNO='2328K0120',CID=3 WHERE ID=12;
UPDATE STUDENTS SET ROLLNO='2328K0121',CID=1 WHERE ID=13;
UPDATE STUDENTS SET ROLLNO='2328K0122',CID=2 WHERE ID=14;
UPDATE STUDENTS SET ROLLNO='2328K0123',CID=3 WHERE ID=15;
UPDATE STUDENTS SET ROLLNO='2328K0124',CID=1 WHERE ID=16;
UPDATE STUDENTS SET ROLLNO='2328K0125',CID=2 WHERE ID=17;
UPDATE STUDENTS SET ROLLNO='2328K0126',CID=3 WHERE ID=18;
UPDATE STUDENTS SET ROLLNO='2328K0127',CID=1 WHERE ID=19;
UPDATE STUDENTS SET ROLLNO='2328K0128',CID=2 WHERE ID=20;
UPDATE STUDENTS SET ROLLNO='2328K0129',CID=3 WHERE ID=21;
UPDATE STUDENTS SET ROLLNO='2328K0130',CID=1 WHERE ID=22;
UPDATE STUDENTS SET ROLLNO='2328K0131',CID=2 WHERE ID=23;
UPDATE STUDENTS SET ROLLNO='2328K0132',CID=3 WHERE ID=24;
4. SELECT *FROM STUDENTS
5. create table course(cid int not null auto_increment,cname varchar(10),primary key(cid));
6. insert into course(cname) values('AIDS'),('CS'),('IT');
7. select *from course;
8. create table marks(mid int not null auto_increment,id int not null,m1 int not null,m2 int not
null,m3 int not null,primary key(mid));
9. insert into marks(id,m1,m2,m3) values
(1,60,85,90),
(2,21,29,94),
(3,100,85,18),
(4,95,52,64),
(5,45,56,72),
(6,25,23,57),
(7,40,55,92),
(8,56,74,80),
(9,47,55,93),
(10,30,35,70),
(11,88,77,66),
(12,85,77,44),
(13,65,45,21),
(14,50,55,60),
(15,80,55,40),
(16,78,95,80),
(17,98,23,40),
(18,90,85,70),
(19,70,33,70),
(20,50,65,90),
(21,90,75,90),
(22,80,35,50),
(23,90,95,98),
(24,80,85,90);
10. select *from marks;
Here we are going to join CNAME column from course table into students table with the help of join
query.
11. select students.name,students.rollno,students.cid from students;
12. select students.name,students.rollno,course.cname from students inner join course on
students.cid=course.cid;
(here we have replace “cname” instead of “cid” using joins)
Multiple Inner joins
13. SELECT students.name,students.rollno,course.cname,marks.M1,marks.M2,marks.M3 FROM
students INNER JOIN course ON students.cid=course.cid
INNER JOIN marks ON students.id=marks.id;
Simple Dynamic Mark list using Queries
Find Total Marks
14. SELECT
students.name,students.rollno,course.cname,marks.M1,marks.M2,marks.M3,(marks.M1+m
arks.M2+marks.M3) As Total_Marks FROM students INNER JOIN course ON
students.cid=course.cid INNER JOIN marks ON students.id=marks.id;
Find Average Mark
15. SELECT
students.name,students.rollno,course.cname,marks.M1,marks.M2,marks.M3,(marks.M1+m
arks.M2+marks.M3) As Total_Marks,(marks.M1+marks.M2+marks.M3)/3 As Average FROM
students INNER JOIN course ON students.cid=course.cid INNER JOIN marks ON
students.id=marks.id;
ROUND
16. SELECT
students.name,students.rollno,course.cname,marks.M1,marks.M2,marks.M3,(marks.M1+m
arks.M2+marks.M3) As Total_Marks,
round((marks.M1+marks.M2+marks.M3)/3,2) As Average FROM students
INNER JOIN course ON students.cid=course.cid INNER JOIN marks ON students.id=marks.id;
FIND RESULT
17. SELECT
students.name,students.rollno,course.cname,marks.M1,marks.M2,marks.M3,(marks.M1+m
arks.M2+marks.M3) As Total_Marks,
round((marks.M1+marks.M2+marks.M3)/3,2) As Average ,
case
when marks.M1>=35 and marks.M2>=35 and marks.M3>=35 then 'PASS'
else 'FAIL'
end
as Result
FROM students
INNER JOIN course ON students.cid=course.cid INNER JOIN marks ON students.id=marks.id;
FIND GRADE
18. SELECT
students.name,students.rollno,course.cname,marks.M1,marks.M2,marks.M3,(marks.M1+m
arks.M2+marks.M3) As Total_Marks,
round((marks.M1+marks.M2+marks.M3)/3,2) As Average ,
case
when marks.M1>=35 and marks.M2>=35 and marks.M3>=35 then 'PASS'
else 'FAIL'
end
as Result ,
case
when marks.M1>=35 and marks.M2>=35 and marks.M3>=35 then
case
when round((marks.M1+marks.M2+marks.M3)/3,2)>=90 and
round((marks.M1+marks.M2+marks.M3)/3,2)<=100 then 'Grade-A'
when round((marks.M1+marks.M2+marks.M3)/3,2)>=80 and
round((marks.M1+marks.M2+marks.M3)/3,2)<=89 then 'Grade-B'
else 'Grade-C'
end
else 'No Grade'
end as Grade
FROM students
INNER JOIN course ON students.cid=course.cid INNER JOIN marks ON students.id=marks.id;
IF u want to view record base on Course?
where course.cname='AIDS'; ( just add this query at the end queries in above)
If u want to view ‘PASS’ result only?
where course.cname='AIDS' and Result='PASS'; ( just add this query in the above example)
( here leads error like “Error Code: 1054. Unknown column 'Result' in 'where clause')
Note : Because here ‘Result’ column is called Dynamic-column(or) Temporary columns .
We can solve this problem with the help of “having” – keyword
where course.cname='AIDS' having Result='PASS'; ( now its works )
where course.cname='AIDS' having Result='PASS' and (Average>=70 and Average<=100);
VIEW
In above queries contains lot of lines
Is there also some dynamic columns (temporary columns) like Total,Average,Result,Grade.
These all are called “ select queries”
We can convert “select query” to virtual table with the help of “view”
Views in SQL are considered as a virtual table. A view also contains rows and columns.
To create the view, we can select the fields from one or more tables present in the
database.
19. CREATE VIEW Reports AS ( just add this line at the beginning of your query)
SELECT
students.name,students.rollno,course.cname,marks.M1,marks.M2,marks.M3,(marks.M1+marks.M2
+marks.M3) As Total_Marks,
round((marks.M1+marks.M2+marks.M3)/3,2) As Average ,
case
when marks.M1>=35 and marks.M2>=35 and marks.M3>=35 then 'PASS'
else 'FAIL'
end
as Result ,
case
when marks.M1>=35 and marks.M2>=35 and marks.M3>=35 then
case
when round((marks.M1+marks.M2+marks.M3)/3,2)>=90 and
round((marks.M1+marks.M2+marks.M3)/3,2)<=100 then 'Grade-A'
when round((marks.M1+marks.M2+marks.M3)/3,2)>=80 and
round((marks.M1+marks.M2+marks.M3)/3,2)<=89 then 'Grade-B'
else 'Grade-C'
end
else 'No Grade'
end as Grade
FROM students
INNER JOIN course ON students.cid=course.cid INNER JOIN marks ON students.id=marks.id where
course.cname='AIDS' having Result='PASS' and (Average>=70 and Average<=100);
(now view created successfully but it not display the table )
In above example ‘Report’ is called view name
20. show tables;
21. show full tables;
To display the view?
22. select *from reports;
23. select rollno,name,Total_Marks,Result from reports;
EX-NO : 1
DATABASE DEVELOPMENT LIFE CYCLE
DATE :
AIM:
To understand the database development life cycle.
The different phases of database development life cycle (DDLC) in the Database
Management System (DBMS) are explained below
1. Database planning
2. System definition
3. Requirement collection and analysis
4. Database design
5. DBMS selection
6. Application design
7. Prototyping
8. Implementation
9. Data conversion and loading
10. Testing
11. Operational maintenance
Lifecycle is a step by step process for creating a Database.
1. Database Planning
Define goals and resources.
Define project objectives.
Identify stakeholders and their needs.
Estimate budget, resource, and time.
Plan for security and scalability.
2. System Definition
Establish System scope and interface.
Establish project scope and boundaries.
Define high-level system requirement.
Identify external systems that need to interact with the database.
3. Requirement Collection and Analysis
Gather user and data requirements.
Conduct interview or surveys with users and stakeholders.
Define data requirements, user needs, and access patterns.
Document functional and non-functional requirements.
4. Database Design
Create the logical and physical structure of the database.
Conceptual Design: Develop an ER-Diagram to represent entities and relationships.
Logical Design: Map the conceptual design to a relational model (tables, keys, constraints).
Physical Design: plan for how the database will be physically stored, optimized for performance
and backed up.
5. DBMS Selection
Choose the database management system.
Evaluate different DBMS option (E.g.: MySQL, Oracle, SQL Server, PostgreSQL).
Consider factors such as data volume, expected traffic and specific features needs.
Select the DBMS that best meets the system’s requirements.
6. Application Design: ( User View)
Design user interface and business logic.
Design the user interface (UI) for interacting with the database ( forms , reports , etc.,)
Define business logics and workflows that interact with the database.
Develop the software architecture and data access layers.
7. Prototyping
Develop and get feedback on a working model.
Build a prototype of the database and key features.
Collect feedback from users to refine requirements and design.
Adjust design based on feedback from the prototype.
8. Implementation
Build the database and application code.
Create database tables, relationships and stored procedures.
Develop the application code to interact with the database.
Perform initial data loading and integration.
9. Data Conversion and loading
Migrate and clean data for the new system.
Extract data from legacy system.
Cleanse, transform and format the data to fit the new database system.
Load the data into the new system and perform validation checks.
10. Testing
Ensure the system works as expected.
Perform unit testing, integration testing and system testing.
Test the database’s performance, security and scalability.
Validate the application’s functionality, including user interactions with the database.
11. Operational Maintenance
Maintain the optimize the system in production.
Monitor system performance and address any issues.
Apply software patches and updates.
Perform regular data backup and ensure disaster recovery plans are in place.
Optimize queries and indexes for performance.
Database Planning
System Definition
Requirements Collection
and Analysis
Database Design
Conceptual Database
Design
Database Application design
Selection
Logical Database
Design
Physical Database
Design
Prototyping Implementation
Data Conversion and
loading
Testing
Operational
Maintenance
Example:
Database Design Development Lifecycle for Railway Reservation System
RAILWAY RESERVATION SYSTEM DEVELOPMENT LIFECYCLE
Cancellation Request
RAILWAY
Filed Reservation Form Reservation
Passenger Trains
RESERVATION Officer
Enquiry SYSTEM
Reservation Chart
Status information
Printed Ticket
RESULT:
Thus database development lifecycle stages are studied and designed a DBDL for railway reservation.
EX-NO : 2
ER-EER MAPPING
DATE :
AIM:
To learn database design using conceptual modelling, Normalization
Consider following databases and draw ER diagram and convert entities and relationships
to relation table for a given scenario.
1. COLLEGE DATABASE:
STUDENT (USN, SName, Address, Phone, Gender)
SEMSEC (SSID, Sem, Sec)
CLASS (USN, SSID)
SUBJECT (Subcode, Title, Sem, Credits)
IAMARKS (USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)
Mapping entities and relationships to relation table (Schema Diagram)
2. COMPANY DATABASE:
EMPLOYEE (SSN, Name, Address, Sex, Salary, SuperSSN, DNo)
DEPARTMENT (DNo, DName, MgrSSN, MgrStartDate)
DLOCATION (DNo,DLoc)
PROJECT (PNo, PName, PLocation, DNo)
WORKS_ON (SSN, PNo, Hours)
RESULT:
Thus the ER-EER mapping was designed and output was verified.
EX-NO : 3 SQL DATA DEFINITION WITH CONSTRAINTS,
VIEWS
DATE :
AIM:
To implement the database using SQL Data definition with constraints, Views
.
Creation, Altering and Dropping of Tables and Inserting Rows into a Table (Use Constraints
While Creating Tables).
DATA TYPES:-
SQL supports following types of data types.
CHAR (SIZE):-
The CHAR data type stores fixed-length character strings.
When you create a table with a CHAR column, you must specify a string length (in bytes or characters)
between 1 and 2000 bytes for the CHAR column width. The default is 1 byte.
VARCHAR (SIZE):-
The VARCHAR data type is synonymous with the VARCHAR2 data type.
NUMBER (L):-
The NUMBER datatype stores fixed and floating-point numbers. Numbers of virtually any magnitude
can be stored and are guaranteed portable among different systems operating Oracle Database, up to 38
digits of precision.
DECIMAL (L, D):-
Numeric data with total number of digits L and number of digits D after decimal point.
DATE:-
The DATE datatype stores point-in-time values (dates and times) in a table. The DATE datatype stores
the year (including the century), the month, the day, the hours, the Minutes, and the seconds (after
midnight).
LONG:-
Character data of variable length which stores up to 2 Gigabytes of data. (A bigger
version the VARCHAR2 datatype).
INTEGER:-
Integer type of Data. It is actually a synonym for NUMBER(38)
FLOAT:-
FLOAT is a 32-bit, single-precision floating-point number datatype. Each FLOAT 8 value requires 5
bytes, including a length byte.
DOUBLE:-
DOUBLE is a 64-bit, double-precision floating-point number datatype. Each DOUBLE value requires 9
bytes, including a length byte.
Data Definition Language (DDL) Commands: -
Create Table
SQL> CREATE TABLE users (id INT NOT NULL AUTO_INCREMENT, name VARCHAR (50)
NOT NULL, age INT NOT NULL, PRIMARY KEY (id));
SQL> DESCRIBE users;
1. Rename the table users as students
SQL> ALTER TABLE users RENAME TO students
Table altered.
SQL> show tables;
2. Add a new column gender with not null constraints to the existing table students
SQL> ALTER TABLE users ADD gender VARCHAR(10) NOT NULL AFTER AGE;
Table altered.
SQL> DESC students;
To insert a multiple columns inside a table?
ALTER TABLE users ADD city VARCHAR (50) NOT NULL, ADD contact VARCHAR (50) NOT
NULL;
SQL> DESC students;
3. All constraints and views that reference the column are dropped automatically, along
With the column.
SQL> ALTER TABLE students DROP column gender
Table altered.
SQL> DESC students;
4. Rename the column NAME to student_NAME in dept table
SQL> ALTER TABLE students RENAME COLUMN NAME TO student_NAME;
Table altered.
SQL> DESC students;
5. Change the size of column contact with size 25
SQL> ALTER TABLE students MODIFY contact VARCHAR(25) NOT NULL;
;
Table altered.
SQL> DESC students;
6. Delete all records in a table
SQL> TRUNCATE TABLE students;
7. Delete Table
SQL> Drop table students;
Table deleted.
RESULT:
The DDL commands have been executed successfully
EX-NO : 4 QUERY THE DATABASE USING SQL
MANIPULATION
DATE :
AIM:
To Query the database using SQL manipulation.
DML commands are the most frequently used SQL commands and is used to query and manipulate the
existing database objects. Some of the commands are.
1. INSERT
This is used to add one or more rows to a table. The values are separated by commas and the data
types char and date are enclosed in apostrophes. The values must be entered in the same order as they are
defined.
2. SELECT
It is used to retrieve information from the table.it is generally referred to as querying the table.
We can either display all columns in a table or only specify column from the table.
3. UPDATE
It is used to alter the column values in a table. A single column may be updated or more than one
column could be updated.
4. DELETE
After inserting row in a table we can also delete them if required. The delete command consists
of a from clause followed by an optional where clause
PROCEDURE
1. INSERT COMMAND
(a) Inserting a single row into a table:
Syntax:
insert into <table name> values (<expression1>,<expression2>)
Example:
SQL> INSERT INTO students VALUES('Ram',25,'Male','Salem','9874563210');
SQL>Select *from students;
(b) To insert a record into a table without mention column names?
SQL> INSERT INTO students VALUES(NULL,'Ravi',23,'Male','Namakkal','9876543210');
SQL> SELECT *from students;
(c) Inserting more than one record using a single insert commands:
Syntax:
insert into <table name> values (&col1, &col2, ….),(&col1,&col2),….
Example
SQL> INSERT INTO students (name, age, gender, city, contact) VALUES
('Ravi',23,'Male','Namakkal','9876543210'),('Sara',23,'Female','Erode','9874521360');
SQL> select *from students
2. SELECT COMMAND
(a) View all rows and all columns
Syntax:
Select * from tablename;
Example:
SQL> select *from students;
(b) Selected Columns and All Rows
Syntax:
Select <column1>,<column2> from tablename;
Example:
SQL> select id,name,age from students ;
(c) Selected Columns And selected Rows
Syntax:
SELECT<column1>, <column2> FROM <tablename> WHERE <condition> ;
Example:
SQL> select *from students where id=1;
(d) Eliminating duplicate rows
Syntax;
SELECT DISTINCT <column1>, <column2> FROM <tablename>
Example:
SQL> SELECT DISTINCT city FROM students;
3. UPDATE COMMAND
(a) Updating records conditionally
SQL> UPDATE students SET city='Hosur',contact='9988776655' WHERE id=2;
SQL> select *from students;
4. DELETE COMMAND
(a) Removal of all rows
Syntax:
Delete from <table name> where <condition>;
Example:
DELETE FROM students WHERE id=3;
RESULT:
The DML commands are executed successfully.
EX-NO : 5
QUERYING/MANAGING THE DATABASE USING SQL
DATE : PROGRAMMING
AIM:
To implement Querying/managing the database using SQL programming – stored procedures/functions
Constraints security using Triggers.
Stored Procedures:-
1. Write a PL/SQL program print serial numbers up to given limit using Stored Procedure
Program
Create database ex5;
Use ex5;
DELIMITER $$
create procedure print_serial_numbers()
BEGIN
DECLARE i INT;
DECLARE str varchar(30);
SET i=1;
SET str='';
krish:loop
if i>10 THEN
leave krish;
end if;
SET str=CONCAT(str,i,' ');
SET i=i+1;
END loop;
select str “Serial Numbers”;
END $$
DELIMITER ;
call print_serial_numbers;
OUTPUT
FUNCTION
2. Write a PL/SQL program to find factorial values for given number using Function
Program
delimiter $$
CREATE FUNCTION factorial(n INT)
RETURNS INT
DETERMINISTIC
BEGIN
declare fact int default 1;
declare cnt int;
set cnt=n;
fact_loop:repeat
set fact=fact*cnt;
set cnt=cnt-1;
until cnt=1
end repeat;
return fact;
END$$
delimiter ;
select factorial(5) "Factorial of Given Number ";
OUTPUT
TRIGGER
1. create table SCM(empid int primary key,empname varchar(30),salary numeric(10,2),gender
varchar(10),dept varchar(30));
2. insert into SCM values
(100,"ABI",15000,"Female","ACC"),
(101,"Babu",5000,"Male","COM"),
(102,"Chinmaie",12000,"Female","SAL"),
(103,"Dinesh",1000,"Male","SAL"),
(104,"Eswari",4000,"Female","COM");
3. select *from SCM;
1. Create another table for transfer the data
create table SCM_Audit_Test(Emp_id int , Operation varchar(100),Inserted_Date date);
select *from SCM_Audit_Test;
2. Create Trigger for AFTER inserted
create trigger SCM_insert
after insert on SCM
for each row
begin
insert into SCM_Audit_Test(Emp_id,Operation,Inserted_Date)
values(new.empid,"INSERT_NEW_RECORD",now());
end $$
delimiter ;
3. Now add new record for checking trigger is working or not
insert into SCM values (109,"joyal",8000,"male","Cbe");
4. Open the second table the output like as following
select *from SCM_Audit_Test;
TRIGGER FOR AFTER UPDATED RECORD INTO A TABLE
BEFORE UPDATE RECORD
select *from SCM;
1. Create another table for storing updated details
create table SCM_Update_Test(id int auto_increment primary key,employee_id int,old_salary
numeric(10,2),new_salary numeric(10,2),Updated_Date timestamp default current_timestamp);
select *from SCM_Update_Test;
2. Create TRIGGER for AFTER UPDATE RECORD IN A TABLE
delimiter $$
create trigger SCM_update
after update on SCM
for each row
begin
insert into SCM_Update_Test(employee_id,old_salary,new_salary)
values(old.empid,old.salary,new.salary);
end $$
delimiter ;
3. Now you can Update record like as following
update SCM set salary=20000 where empid=101;
update SCM set salary=15000 where empid=103;
update SCM set salary=18000 where empid=109;
4. Now you can view the Update_table
select *from SCM_Update_Test;
RESULT:
The Stored Procedure, Function and Trigger has been executed successfully.
EX-NO : 6
DATABASE DESIGN USING NORMALIZATION
DATE :
AIM:
To implement Database design using Normalization – Bottom-up approach.
Database Normalization
Normalization is the process of organizing data in a database to reduce redundancy (repeated
values) and improve data integrity.
Data redundancy in DBMS means having the same data at multiple places.
It is necessary to remove data redundancy because it causes anomalies (it means error) in a
database which makes it very hard for a database administrator to maintain it.
If u want to remove duplicate values in a DB then you need to use Normalization technique.
Example:
Database_name : college
Table_name : student
Name Roll_no Section
John 21 A
John 21 A
Joshua 22 B
Joyal 23 C
In above table (Name: John and Age: 21 and Section: A) repeated twice, this is known as data
redundancy.
Data redundancy is nothing but duplicate values, if you want to remove duplicate values in your
DB then you need to use Normalization technique.
The main reason for normalizing the table is to remove these anomalies.
Failure to remove anomalies leads to data redundancy and can cause data integrity and other
problems as database grows.
There are different Normal forms (NF) in Normalization
1. 1NF
2. 2NF
3. 3NF
4. BCNF
Important Key points of all NF forms
1NF: Ensure atomic values (single values).
2NF: Remove partial dependencies.
3NF: Remove transitive dependencies.
BCNF: Ensure that every determinant is a super key.
1NF (First Normal Form)
A table is in 1NF if:
1. All columns contain atomic values (indivisible) values.
2. Each column contains values of a single type.
3. Each records need to be unique.
4. First Normal Form disallows multi-valued attribute, composite attribute & their combinations.
Example-1:
Student_ID Name Courses
101 Alice Math , Science
102 Bob English , History
103 Charlie Maths , English
The above table is not in 1NF because the “courses” column contains multiple values.
Convert to 1NF by splitting the courses into separate rows:
Student_ID Name Courses
101 Alice Math
101 Alice Science
102 Bob English
102 Bob History
103 Charlie Maths
103 Charlie English
Now, each column has atomic (single) values, so the table is in 1NF.
Example-2
Employee_code Employee_name Employee_Mobile_Number
1001 Krish 9994974215 , 9994477610
1002 Mahesh 9994477191 , 9894768026
1003 Daniel 9994962905 , 6385753519
1004 Mani 9894585056 , 9894123442
The above table is not in 1NF because the “Employee_Mobile_numbers” column contains multiple
values.
Convert to 1NF by splitting the Employee_mobile_number into separate rows:
Employee_code Employee_name Employee_mobile_number
1001 Krish 9994974125
1001 Krish 9994477610
1002 Mahesh 9994477191
1002 Mahesh 9894768026
1003 Daniel 9994962905
1003 Daniel 6385753519
1004 Mani 9894585956
1004 Mani 9894123442
Now, each column has atomic (single) values, so the table is in 1NF.
2NF(Second Normal Form)
It is in 1NF ( The table should be in the First normal form)
Every non-key column is fully functionally dependent on the primary key ( i.e: No partial
dependency).
There should be no “partial dependency”.
No partial dependency means primary key column should not contain duplicate values.
All non-prime attributes are fully functionally dependent on the primary key.
Example-1
Consider the table:
Student_ID Course Instructor Instructor_Phone
1001 Math Mr.Rajesh 12324343
1001 Science Mr.Babu 45536560
1002 English Mr.John 99999999
1002 History Mr.Sam 12132232
Here, the primary key is a combination of student_ID and Course.
The non-key attribute is instructor_phone , It fully depends only on Instructor is called fully
functionally dependent.
The non-key attribute(Instructor_Phone) is not dependent on the fully primary
key(Student_ID).
To convert the above table as 2NF , break the table into two:
Table1: student_course
Student_ID Course Instructor
1001 Math Mr.Rajesh
1001 Science Mr.Babu
1002 English Mr.John
1002 History Mr.Sam
Table-2 : instructor_details ( non-key attributes )
Instructor Instructor_Phone
Mr.Rajesh 12324343
Mr.Babu 45536560
Mr.John 99999999
Mr.Sam 12132232
Now the above table is in 2NF
Example-2:
Employee_code Project_ID Employee_name Project_name
101 PID3 John Project102
101 PID1 John Project101
102 PID4 Riyan Project_104
103 PID5 Rahul Project_102
Here , “partial dependency” having because it is not a 2NF
Here , Project_name dependent on Project_ID , not dependent on Employee_code is known as
“partial dependency”
Convert the above table as 2NF
Table-1: Employee_details
Employee_code Employee_name
101 John
101 John
102 Riyan
103 Rahul
Table-2: Project_details
Project_ID Project_name
PID3 Project102
PID1 Project101
PID4 Project_104
PID5 Project_102
Now the above table is in 2NF
3NF (Third Normal Form)
A table is in 3NF if:
It is in 2NF.
There is no transitive dependencies (i.e: Non-key columns should not depend on other non-key
columns).
Transitive dependencies, when one column depends on a columns which is not primary key is called
transitive dependencies.
Example-1:
Employee_Code Employee_name Employee_ZIPCODE Employee_City
101 John 641654 Tirpur
102 Rahul 641008 Cbe
103 Vishnu 600018 Chennai
Here , Employee_code determine (Employee_name,Employee_ZIPCODE,Employee_city)
Here , Employee_ZIPCODE will determine Employee_City is called ( Transitive dependencies ) but
in 3NF (there is no Transitive dependencies ).
Convert the above table as 3NF
Example-1
Table-1: Employee_details
Employee_Code Employee_name Employee_ZIPCODE
101 John 641654
102 Rahul 641008
103 Vishnu 600018
Table-2: Employee_location
Employee_ZIPCODE Employee_City
641654 Tirpur
641008 Cbe
600018 Chennai
Now the above table is in 3NF
Example-2:
EmpID F_Name L_Name DOB Dept_ID Dept_Name
1001 Aishwarya Rajes 2005-04-24 11 Engineering
1002 Anand Venkat 2005-05-22 12 Finance
1003 Bala Sundaram 2004-11-02 11 Engineering
1004 Deepa Mani 2004-11-27 13 Sales
Here ,( F_name , L_Name , DOB , Dept_id ) are dependent on EMP_ID
Here (Dept_Name is dependent on Dept_ID) so here Dept_Name is non primary is dependent on
another non-primary key (i.e: Dept_ID) is called Transitive dependency.
Table-1:
EmpID F_Name L_Name DOB Dept_ID
1001 Aishwarya Rajes 2005-04-24 11
1002 Anand Venkat 2005-05-22 12
1003 Bala Sundaram 2004-11-02 11
1004 Deepa Mani 2004-11-27 13
Table-2
Dept_ID Dept_Name
11 Engineering
12 Finance
13 Sales
BCNF (Boyce-codd Normal form) – or – 3.5 NF
A table is in BCNF if:
It is in 3NF
For every functional dependency, the left side (determinant) is a super key.
For any dependency AB , A should be a “super key”
Here A is the super key of the table. That means A cannot be a non-primary key attribute if B is a
Prime Attribute.
Example
Roll_no Stu_name Branch_id Branch_name
101 Sai 121 CSE
102 Shiva 122 AIML
103 Sharma 123 CS
104 Raju 121 CSE
When roll_no stu_name
If stu_name dependent on Roll_no , the roll_no must be super key.
Here branch_nameBranc_id
If branc_name depedent on brach_id , the branch_id must be super key
Super key must contains unique values but here we have two record having (branch_id:121)
So here Branch_id is not a super_key , so this table is not a BCNF because branch_id is not a super
key
Convert the above table as BCNF
Table-1:
Roll_no Stu_name
101 Sai
102 Shiva
103 Sharma
104 Raju
Table-2 :
Branch_id Branch_name
121 CSE
122 AIML
123 CS
QUERIES
1. CREATE TABLE COURSE(Course_ID int primary key,Course_Name varchar(30),Staff_Name varchar(30));
2. Insert into COURSE(Course_ID,Course_Name,Staff_Name) values(401,”CS”,”Mr.Krishnan”),
(402,”IT”,”Mr.Nisar”),(403,”AIDS”,”Dr.Ramesh”),(404,”Maths”,”Dr.Sanjay”);
3. Select *from COURSE;
4. CREATE TABLE STUDENT(Student_ID int primary key,Student_Name varchar(30),DOB date , Gender
varchar(10),Course_ID int FOREIGN KEY references COURSE(Course_ID));
5. INSERT into STUDENT values(1001,”Joshua”,”2005-04-24”,”Male”,401);
6. Select *from STUDENT;
7. INSERT into STUDENT values(1002,”Jack”,”2005-05-2”,”Male”,405);
8. Delete from COURSE where Course_ID=401;
9. Delete from STUDENT where Course_ID=401;
OUTPUT
COURSE
Course_ID Course_Name Staff_Name
401 CS Mr.Krishnan
402 IT Mr.Nisar
403 AIDS Dr.Ramesh
404 Maths Dr.Sanjay
STUDENT
Student_ID Student_Name DOB Gender Course_ID
1001 Joshua 24-4-2005 Male 401
1002 Jack 22-05-2005 Male 402
1003 Sarah 11-02-2004 Female 403
1004 Preethi 9-12-2004 Female 404
Result:
Thus, we implemented database design using Normalization with bottom up approach
EX-NO : 7 DEVELOP DATABASE APPLICATIONS USING IDE
TOOLS
DATE : (EG., NETBEANS,MySQL)
AIM:
To create a Database Driven applications with Java Netbean with MySQL.
ALGORITHM:
Step-1: Open Mysql and create the DB like as Following
Database name : studentrecord
Table Name : marklist
Field Name Data type
RollNo Integer
Names Varchar(30)
M1 Numberic(5,2)
M2 Numberic(5,2)
M3 Numberic(5,2)
Tot Numberic(5,2)
Ave Numberic(5,2)
Result Varchar(20)
Queries
1. Create database and table like as following
create database studentrecord;
use studentrecord;
2. Insert record into table
create table marklist(RollNo int primary key , Names varchar(30),m1 numeric(5,2)
,m2 numeric(5,2),m3 numeric(5,2),Tot numeric(5,2),ave numeric(5,2),Result varchar(20));
3. View table
Select *from marklist
Step-2: Open Net Bean
1. Create a project like as following
File New Project click java Application click Next
Project name: StudentReport
Project Location : E:\ Finish
2. Create a new form like as following
Right click on projectname (Ex:StudentReport) newJFrame form
Class name : resultform click finish
now form will Appear on the screen ,drag necessary labels and textboxes and buttons
3. If you want Edit text for control ?
Just right click on control click edit text
4. If you want to give name for control ?
Just right click on control click change variable name
Control Text Variable Name
JTextField -1 Rno
JTextField -2 Name
JTextField -3 Sub1
JTextField -4 Sub2
JTextField -5 Sub3
JTextField -6 Total
JTextField -7 Average
JTextField -8 Result1
JButton-1 Result
JButton-2 Insert
JButton-3 Update
JButton-4 Delete
JButton-5 Search
Now form will be like as following
Step-3: How to Make connection drive
1. Go to window menu click Services (Ctrl+5)
2. Right click on word (Database) New Connection
3. Driver : MYSQL(Connector/J/driver)
4. See below we got a link (i.e: http://dev.mysql.com/downloads/connector/j/)
5. Visit this link
6. We got the web page like as following
7. In Selection Operating System Drop down box take ( Platform independent)
8. Now we got the page like as following
9. Click Download the 2-nd file (i.e: 4.8M – file )
10. We got the another page like as following
11. Finally click ( No thanks ,just Start my download ) . …
12. Now we got the Zip file (i.e: mysql-connector-java-8.0.27.zip)
13. Copy it and paste into some where you wish
14. Then right click on Zip file and click extract File click ok
15. Wait few minutes … now we got a folder (mysql-connector-java-8.0.27)
16. Open it and see there is a file called (mysql-connector-java-8.0.27.jar)
Step-4: Now again try to Make Connection Drive
1. Go to window menu click Services (Ctrl+5)
2. Right click on word (Database) New Connection
3. Driver : MYSQL(Connector/J/driver)
4. Click Add choose your mysql jar-file location
5. Ex: E:\Employees\mysql-connector-java-8.0.27
6. Select mysql-connector-java-8.0.27.jar – file
7. Then select E:\Employees\mysql-connector-java-8.0.27\ mysql-connector-java-8.0.27.jar
8. Click next
9. Check the following instructions
Driver Name : MySQL(Connector/J Driver)
Host : localhost Port: 3306
Database : studentrecord
User Name : root
Password : while you have installed
Click ( Test Connection ) …. If you all the above information is true means we go the
message ( i ) – Connection Succeeded..
Finally click finish
10. Now we got the link in the services section like as following
11. jdbc:mysql://localhost:3306/peacock?zeroDateTimeBehavior=convertToNull [root on Default
schema]
Step-5:Now Add Jar-file also in our Project
1. Right click on our Project name (Employees) Click Properties
2. Click Libraries click Add JAR/Folder
3. choose your mysql jar-file location
4. Ex: E:\Employees\mysql-connector-java-8.0.27
5. Select mysql-connector-java-8.0.27.jar – file press ok
Step-6: Double click on Result Button and type the following codes
private void resultActionPerformed(java.awt.event.ActionEvent evt) {
String s1 = sub1.getText();
String s2 = sub2.getText();
String s3 = sub3.getText();
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int n3 = Integer.parseInt(s3);
if(n1>35&&n2>35&&n3>35&&n1<100&&n2<=100&&n3<=100)
{
int t = n1+n2+n3;
float avg = (float)t/3;
total.setText(""+t);
average.setText(""+avg);
result1.setText("PASS");
}
else
{
result1.setText("FAIL/INVALID DATA");
total.setText("");
average.setText("");
}}
To run the Form : Press Shift + F6 ( the form getting result like as following )
Step-6: Insert records in to the Mysql Table
Double click INSERT button and type the following codes
private void insertActionPerformed(java.awt.event.ActionEvent evt) {
try
{
String reg = Rno.getText();
int r=Integer.parseInt(reg);
String name1 = Name.getText();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentrecord","root","Krishnan@90") ;
PreparedStatement pst = con.prepareStatement("insert into marklist values (?,?,?,?,?,?,?,?)");
pst.setInt(1, r);
pst.setString(2, name1);
pst.setInt(3,Integer.parseInt(Sub1.getText()));
pst.setInt(4,Integer.parseInt(Sub2.getText()));
pst.setInt(5,Integer.parseInt(Sub3.getText()));
pst.setInt(6, Integer.parseInt(Total.getText()));
pst.setFloat(7, Float.parseFloat(Average.getText()));
pst.setString(8, Result1.getText());
int count = pst.executeUpdate();
System.out.println("Record Inserted");
pst.close();
con.close();
}
catch(SQLException se)
{
System.out.println("Error "+se);
}}
To run the Form : Press Shift + F6 ( the form getting result like as following )
Step-7: Search record from Mysql Table
Double click on Search button
private void searchActionPerformed(java.awt.event.ActionEvent evt) {
String s1=JOptionPane.showInputDialog("Enter Roll Number ");
int r1=Integer.parseInt(s1);
try
{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentrecord","root","Krishnan@90") ;
Statement s = con.createStatement();
ResultSet rs;
String se="select *from marklist where RollNo="+r1;
rs=s.executeQuery(se);
while(rs.next())
{
Rno.setText(""+rs.getInt(1));
Name.setText(""+rs.getString(2));
Sub1.setText(""+rs.getInt(3));
Sub2.setText(""+rs.getInt(4));
Sub3.setText(""+rs.getInt(5));
Total.setText(""+rs.getInt(6));
Average.setText(""+rs.getFloat(7));
Result1.setText(""+rs.getString(8));
}
s.close();
con.close();
}
catch(SQLException se)
{
System.out.println("Error "+se);
}
}
To run the Form : Press Shift + F6 ( the form getting result like as following )
Step-8: Delete Record From a Table in Mysql
Double click Delete button
private void deleteActionPerformed(java.awt.event.ActionEvent evt) {
String s1=JOptionPane.showInputDialog("Enter Roll Number to Delete ");
int r1=Integer.parseInt(s1);
try
{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentrecord","root","Krishnan@90") ;
Statement s = con.createStatement();
String se="delete from marklist where RollNo="+r1;
int rs=s.executeUpdate(se);
JOptionPane.showMessageDialog(rootPane, "Record Deleted");
s.close();
con.close();
}
catch(SQLException se)
{
System.out.println("Error "+se);
}
}
To run the Form : Press Shift + F6 ( the form getting result like as following )
Step-9: Update record from a table
Double click on Update button
private void UpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
String s1=JOptionPane.showInputDialog("Enter Id number to Modify");
int r1=Integer.parseInt(s1);
Rno.setText(""+r1);
String n=JOptionPane.showInputDialog("Enter New Name");
Name.setText(""+n);
String n1=JOptionPane.showInputDialog("Enter New Mark1");
int m1=Integer.parseInt(n1);
Sub1.setText(""+m1);
String n2=JOptionPane.showInputDialog("Enter New Mark2");
int m2=Integer.parseInt(n2);
Sub2.setText(""+m2);
String n3=JOptionPane.showInputDialog("Enter New Mark3");
int m3=Integer.parseInt(n3);
Sub3.setText(""+m3);
int t = m1+m2+m3;
float avg = (float)t/3;
Total.setText(""+t);
Average.setText(""+avg);
If(m1>=35 && m2>=35 && m3>=35)
{
Result1.setText("PASS");
}
else
{
Result1.setText("Fail");
}
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentrecord","root","Krishnan@90") ;
PreparedStatement pst=con.prepareStatement("update marklist set sname=?,m1=?,m2=?,m3=?,tot=?,ave=?,result=? where RollNo=?");
pst.setString(1,n);
pst.setInt(2,m1);
pst.setInt(3,m2);
pst.setInt(4,m3);
pst.setInt(5,t);
pst.setFloat(6,avg);
pst.setString(7,Result1.getText());
pst.setInt(8,r1);
int c=pst.executeUpdate();
System.out.println("Record Updated");
con.close();
pst.close();
}
catch(SQLException se)
{
System.out.println("Error:"+se);
}
}
RESULT:
Thus database driven application was successfully created using NetBeans IDE with Mysql.
EX-NO : 8 DEVELOP EMPLOYEE DATABASE USING VARIOUS
QUERIES ( COMPARISON , LOGICAL , SET ,
DATE : SORTING , GROUPING OPERATORS )
AIM:
To implement Employee Database using various operations (set, sorting, grouping)
.
ALGORITHM:
QUERIES
Step-1: Create tables Employee and personal
create table Employee(empno int primary key,Name varchar(30),designation varchar(30),
gender varchar(10),age int,DOJ date,salary numeric(10,2));
create table personal(empno int primary key , Name varchar(30),DOB date);
Step-2: Insert Record into Employee Table and Perosonal
insert into Employee values
(101, "Arun","Manager","Male",45,"1990-08-12",28500),
(102,"Zaheer","Accountant","Male",25,"1995-02-15",8500),
(103,"Krish","Developer","Male",35,"2000-09-06",15500),
(104,"sarah","Manager","FeMale",19,"2002-03-25",20500),
(105,"Madheena","Developer","FeMale",33,"2004-02-07",12500),
(106,"Vishnu","Accountant","Male",20,"2009-08-28",18500),
(107,"Rahul","Manager","Male",29,"2007-08-18",30500),
(108,"Jenifer","Developer","FeMale",35,"2007-07-11",9500),
(109,"Moses","Manager","Male",35,"1989-08-1",20700);
insert into personal values
(101,"Arun","1990-02-09"),
(102,"Zaheer","1988-04-15"),
(103,"Krish","1990-02-09"),
(104,"sarah","1988-01-29"),
(105,"Madheena","1989-08-18"),
(106,"Vishnu","1992-06-20"),
(107,"Rahul","1988-01-22"),
(108,"Jenifer","1990-01-20"),
(109,"Moses","1979-02-10"),
(110,"JOHN","1990-01-19");
Step-3: View table Employee and Personal
select *from Employee;
Select *from personal;
VARIOUS OPERATIONS
1. Comparison Operation
select *from Employee where age>30;
select *from Employee where age<30;
2. Logical operation
select *from Employee where age>30 AND gender="FeMale";
select *from Employee where age<40 AND (designation="Accountant" OR designation="Developer");
select *from Employee where (designation<>"Developer" AND designation<>"Manager");
3. Set operation
UNION
select empno,Name from Employee union select empno,Name from personal;
INTERSECT
select empno,Name from Employee intersect select empno,Name from personal;
EXCEPT
select empno,Name from personal except select empno,Name from Employee;
4. GROUP BY
select designation,sum(salary) from Employee group by designation;
select gender,sum(salary) from Employee group by gender;
5. SORT
select *from EMployee order by Name;
select *from EMployee order by salary;
select *from EMployee order by age desc;
select *from EMployee order by gender;
RESULT:
The Above Result has been obtained successfully.
EX-NO : 9
DEVELOP INVENTORY DATABASE USING PL/SQL
DATE :
AIM:
To implement inventory database using PL/SQL.
ALGORITHM:
QUERIES
Step-1: Create inventory table
create table inventory(pid int primary key,pname varchar(30),rate numeric(10,2));
Step-2: Insert records into inventory table
insert into inventory values(100,"PEN",80),(101,"PENCIL",10),(102,"BOX",150),
(103,"BOOK",350),(104,"SKETCH",50),(105,"PENDRIVE",600);
Step-3:View Table ( Before Update 20% )
Select *from inventory;
Step-4: Write PL/SQL for Update 20% rate for all products
delimiter $$
create procedure update_Rate()
begin
declare done int default 0;
declare upid int;
declare uprate numeric(10,2);
declare upname varchar(30);
declare cur cursor for select *from inventory;
declare exit handler for not found set done=1;
open cur;
upinv:loop
if done=1 then
leave upinv;
end if;
fetch cur into upid,upname,uprate;
set uprate=uprate+((uprate*20)/100);
update inventory set rate=uprate where pid=upid;
end loop;
close cur;
end $$
delimiter ;
call update_Rate();
select *from inventory;
Step-5: Adding new filed (Number_of_Item) using Alter command
alter table inventory add column Number_of_Items int;
select *from inventory;
Step-6:Place values for Number_of_items in All Records in Table
update inventory set Number_of_Items=15 where pid=100;
update inventory set Number_of_Items=5 where pid=101;
update inventory set Number_of_Items=25 where pid=102;
update inventory set Number_of_Items=6 where pid=103;
update inventory set Number_of_Items=13 where pid=104;
update inventory set Number_of_Items=22 where pid=105;
select *from inventory;
OUTPUT
RESULT:
The Above Result has been obtained successfully.
EX-NO : 10
OBJECT RELATIONAL DATABASE USING
OBEJCT QUERY LANGUAGE
DATE :
AIM:
To write query for object relational database using object query language.
Object Query Language:
Query Object Language (OQL) is a version of the Structured Query Language (SQL) that has been
designed for use in Network Manager. The components create and interact with their databases using OQL.
Use OQL to create new databases or insert data into existing databases (to configure the operation
of Network Manager components) by amending the component schema files. You can also issue OQL
statements using the OQL Service Provider, for example, to create or modify databases, insert data into
databases and retrieve data.
Database and table creation
You can create databases and tables with the create command. You
can issue the create command to create a database. create database
database_name ;
create table database_name.table_name (
column_name [ constraints ] [ default default ] ,
[ column_name [ constraints ] [ default default ] , ] [
additional_columns ]
[ unique ( column_name ) , ] [
counter ( column_name ) , ]
[ timestamp ( column_name ) ]
);
Examples of database and table creation
create database staff; // creates the staff database
The following insert defines the managers table.
create table staff.managers
(
EmployeeIDint NOT NULL PRIMARY KEY,
Name text NOT NULL,
Department text default "Sales",
Gender text,
Age int,
unique ( EmployeeID ) // indicates that the data in the
// EmployeeID column must be unique.
);
For the managers table:
The EmployeeID and Name columns cannot be NULL.
The EmployeeID column is the primary key and must be unique.
If no value is inserted into the Department column for a given record it takes the value "Sales".
Example 2
The following insert creates the staff.employees table.
create table staff.employees
(
EmployeeIDint NOT NULL PRIMARY KEY,
Name text NOT NULL,
Skills list type text,
Gender text,
Age int // There is no comma here because this
// is the last entry.
);
For the staff.employees table:
The EmployeeID and Name columns cannot be NULL.
The Skills column is a list of text strings.
Example 3
The following insert creates the staff.contractors table.
create table staff.contractors
(
EmployeeIDint NOT NULL PRIMARY KEY,
Name text NOT NULL,
Gender text,
Age int,
ExtraInfo object type vblist,
volatile
);
For the staff.contractors table:
The ExtraInfo column contains a list of varbinds.
Selecting data from a table
QSyntax
The following syntax shows how to use the select keyword to retrieve data from a table.
select comma_separated_column_list_or_wildcard
from database_name.table_name
[ where conditional_test ]
[ order by field_name[asc|desc] ];
The * symbol can be used as a wildcard in a select statement to return all the columns of the table.
Alternatively a comma-separated list of columns can be specified.
If you specify an order by clause, then results are returned in ascending order by default. NULL
values are returned first when the results are in ascending order. Ordering of results in descending
order is the exact opposite of the ordering of results in ascending order.
Example 1
The following example shows how to use the select statement within the OQL Service Provider to
query the staff.managers table (the following example output is abbreviated).
|phoenix:1.>select * fromstaff.managers;
|phoenix:2.>go
.....
{
EmployeeID=1;
Name='Matt';
Department='Development';
Gender='M';
Age=28;
}
{
EmployeeID=2;
....
....
}
( 5 record(s) : Transaction complete )
Example 2
The following example shows a select statement that retrieves only specific fields from
the staff.managers table.
|phoenix:1.>select Name, Gender fromstaff.managers;
|phoenix:2.>go
.....
{
Name='Matt';
Gender='M';
}
{
Name='Irene';
Gender='F';
}
{
Name='Ernie';
....
....
}
( 5 record(s) : Transaction complete )
Example 3
The following example uses a where clause to restrict the results.
|phoenix:1.>selectEmployeeID, Name fromstaff.managers
|phoenix:2.>where Department = "Marketing";
|phoenix:3.>go
.
{
EmployeeID=4;
Name='John';
}
( 1 record(s) : Transaction complete )
Example 4
The following example shows how to use a select DISTINCT keyword to retrieve a single row
for each type of data; for example a single row for each department.
|phoenix:1.>select DISTINCT Department fromstaff.managers
|phoenix:2.>go
.
{
Department='Development';
}
{
Department='Marketing';
}
{
Department='Sales';
}
( 3 record(s) : Transaction complete )
query the data in a table using the select keyword. Use these examples to help you use the select
keyword.
RESULT:
Thus the query for object relational database using object query language was created and
executed.