DBMS LAB ALL Programs
DBMS LAB ALL Programs
Open Database?
2. Use sec_aids;
Drop Database?
3. Drop database sec_aids;
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 rename a table?
15. ALTER TABLE users RENAME TO students;
16. Show tables;
7. SELECT name,age,city FROM students WHERE (city='Namakkal' OR city='Hosur') AND age >=
23;
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;
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;
INNER JOIN
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
('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');
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
While using joins we want to mention dot operator as prefix in each fields of the table like
Result:
Id Id
1 1
2 2
3 3
4 4
RESULT
FIND “sep” month updated salary details (LEFT join)
RIGHT JOIN
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 .
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;
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;
CASE
ELSE 0
END
CASE
ELSE 0
END
CASE
ELSE 0
END
(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);
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;
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;
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,
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
else 'FAIL'
end
as Result
FROM students
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
else 'FAIL'
end
as Result ,
case
case
else 'Grade-C'
end
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'; ( just add this query at the end queries in above)
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')
VIEW
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
else 'FAIL'
end
as Result ,
case
case
else 'Grade-C'
end
end as Grade
FROM students
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
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.
System Definition
Requirements Collection
and Analysis
Database Design
Conceptual Database
Design
Database Application design
Selection
Logical Database
Design
Physical Database
Design
Prototyping Implementation
Testing
Operational
Maintenance
Example:
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:
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)
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.
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));
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.
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.
7. Delete Table
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
Example:
SQL> INSERT INTO students VALUES('Ram',25,'Male','Salem','9874563210');
(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');
Example:
SQL> select *from students;
4. DELETE COMMAND
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;
begin
end $$
delimiter ;
delimiter $$
begin
end $$
delimiter ;
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.
1. 1NF
2. 2NF
3. 3NF
4. BCNF
Important Key points of all NF forms
Example-1:
The above table is not in 1NF because the “courses” column contains multiple values.
Now, each column has atomic (single) values, so the table is in 1NF.
Example-2
The above table is not in 1NF because the “Employee_Mobile_numbers” column contains multiple
values.
Now, each column has atomic (single) values, so the table is in 1NF.
To convert the above table as 2NF , break the table into two:
Table1: student_course
Instructor Instructor_Phone
Mr.Rajesh 12324343
Mr.Babu 45536560
Mr.John 99999999
Mr.Sam 12132232
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
Example-1
Table-1: Employee_details
Table-2: Employee_location
Employee_ZIPCODE Employee_City
641654 Tirpur
641008 Cbe
600018 Chennai
Table-1:
Table-2
Dept_ID Dept_Name
11 Engineering
12 Finance
13 Sales
BCNF (Boyce-codd Normal form) – or – 3.5 NF
Example
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));
(402,”IT”,”Mr.Nisar”),(403,”AIDS”,”Dr.Ramesh”),(404,”Maths”,”Dr.Sanjay”);
COURSE
401 CS Mr.Krishnan
402 IT Mr.Nisar
STUDENT
Result:
AIM:
To create a Database Driven applications with Java Netbean with MySQL.
ALGORITHM:
Step-1: Open Mysql and create the DB like as Following
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
now form will Appear on the screen ,drag necessary labels and textboxes and buttons
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
Click ( Test Connection ) …. If you all the above information is true means we go the
message ( i ) – Connection Succeeded..
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
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
AIM:
To implement Employee Database using various operations (set, sorting, grouping)
.
ALGORITHM:
QUERIES
1. Comparison Operation
select *from Employee where age>30;
2. Logical operation
select *from Employee where age>30 AND gender="FeMale";
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;
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-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();
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.
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.
You can create databases and tables with the create command. You
database_name ;
additional_columns ]
[ unique ( column_name ) , ] [
counter ( column_name ) , ]
[ timestamp ( column_name ) ]
);
Examples of database and table creation
Example 2
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.
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.
RESULT:
Thus the query for object relational database using object query language was created and
executed.