0% found this document useful (0 votes)
74 views43 pages

DBMS Lab File

Here are the steps to create a cursor in MySQL: 1. Declare the cursor: DECLARE cursor_name CURSOR FOR SELECT statement; 2. Open the cursor: OPEN cursor_name; 3. Fetch data from the cursor: FETCH cursor_name INTO variable_list; 4. Close the cursor: CLOSE cursor_name; For example: DECLARE emp_cursor CURSOR FOR SELECT emp_id, name FROM employees; OPEN emp_cursor; FETCH NEXT FROM emp_cursor INTO @emp_id, @name; PRINT @emp_id, @name; FET

Uploaded by

prabhu bhakti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
74 views43 pages

DBMS Lab File

Here are the steps to create a cursor in MySQL: 1. Declare the cursor: DECLARE cursor_name CURSOR FOR SELECT statement; 2. Open the cursor: OPEN cursor_name; 3. Fetch data from the cursor: FETCH cursor_name INTO variable_list; 4. Close the cursor: CLOSE cursor_name; For example: DECLARE emp_cursor CURSOR FOR SELECT emp_id, name FROM employees; OPEN emp_cursor; FETCH NEXT FROM emp_cursor INTO @emp_id, @name; PRINT @emp_id, @name; FET

Uploaded by

prabhu bhakti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 43

G.L.

BAJAJ INSTITUTE OF TECHNOLOGY & MANAGEMENT,


GREATER NOIDA

Database Management System Lab


(KCS-551)

LAB FILE
ACADEMIC SESSION 2023-24

COURSE: B.TECH (ACSE)


SEM: V

Dept. of Applied Computational Science & Engineering


List of Experiments

S. No. Experiments

1 Installing Oracle

2 Creating Entity-Relationship Diagram using case tools.

Writing SQL statements Using ORACLE /MYSQL:


a) Writing basic SQL SELECT statements.
b) Restricting and sorting data.
c) Displaying data from multiple tables.
3
d) Aggregating data using group function.
e) Manipulating data.
f) Creating and managing tables.

4 Normalization
Creating cursor
5
Creating procedure and functions
6

7 Creating packages and triggers

8 Design and implementation of payroll processing system

9 Design and implementation of Library Information System

10 Design and implementation of Student Information System

11 Automatic Backup of Files and Recovery of Files


ExperimentNo:1
ProgramName:InstallingOracle

TheoryConcept:Toinstallthesoftware,youmustusetheUniversalinstaller.

Implementation:

1. For this installation, you need either the DVDs or a downloaded version of the DVDs. In
thistutorial, you install from the downloaded version. From the directory where the DVD files
wereunzipped,openWindowsExploreranddouble-clickonsetup.exefromthe\db\Disk1directory.

2. TheproductyouwanttoinstallisDatabase11g.Makesuretheproductisselectedandclick
Next.

3. Youwillperformabasicinstallationwithastarterdatabase.EnterorclfortheGlobalDatabaseName
and for Database Password and Confirm Password.Then, clickNext
4. Configuration Manager allows you to associate your configuration information with
yourMetalinkaccount.Youcanchoosetoenableitonthiswindow.Then,clickNext.
5. Review the Summary window to verify what is to be installed.Then, clickInstall.

6. The progress window appears.


7. The ConfigurationAssistants window appears.

8. Yourdatabaseisnowbeingcreated.
9. When the database has been created, you can unlock the users you want to use. Click OK.

10. ClickExit.ClickYestoconfirmexit.
ExperimentNo:2

ProgramName: Creating Entity-Relationship Diagram using case tools.

Steps:

Step 1: Install MySQL Workbench


If you don't already have MySQL Workbench installed, you can download it from the official
MySQL website: https://www.mysql.com/products/workbench/

Step 2: Launch MySQL Workbench


After installation, launch MySQL Workbench on your computer.

Step 3: Create a New EER Diagram

Click on "File" in the menu bar.


Select "New Model" to create a new Entity-Relationship Diagram (ERD).
Step 4: Add Entities and Attributes

In the diagram canvas, you can add entities by clicking on the "Entity" button in the toolbar and
then clicking on the canvas to place the entity.
Double-click on the entity to give it a name.
To add attributes to an entity, right-click on the entity and select "Add Attribute."

Step 5: Define Relationships

To define relationships between entities, select the "Relationship" tool from the toolbar.
Click on one entity and then click on the related entity to establish a relationship.
Specify the cardinality and other properties of the relationship.
Step 6: Save Your ERD

It's important to save your work. Click on "File" and then "Save" to save the model.

Step 7: Generate SQL Script (Optional)

MySQL Workbench allows you to generate SQL scripts from your ERD. You can do this by
clicking on "Database" and then "Forward Engineer..." to create a database schema based on your
ERD.
Step 8: Review and Export (Optional)

You can review your ERD, make any necessary changes, and then export it in different formats,
such as PNG or PDF.
Output Examples:
Experiment No: - 3

ProgramName: Writing SQL statements Using ORACLE /MYSQL:


a)Writing basic SQL SELECT statements.
b) Restricting and sorting data.
c) Displaying data from multiple tables.
d) Aggregating data using group function.
e) Manipulating data.
f) Creating and managing tables.

SQL statements using MYSQL:

a) Writing basic SQL SELECT statements.

-- Select all columns from a table


SELECT * FROM employees;

-- Select specific columns from a table


SELECT first_name, last_name FROM employees;

-- Select distinct values from a column


SELECT DISTINCT department_id FROM employees;

-- Select data with a filter (WHERE clause)


SELECT * FROM employees WHERE salary > 50000;

-- Select data with a combination of conditions


SELECT * FROM employees WHERE department_id = 2 AND salary > 50000;

b) Restricting and sorting data.

-- Sorting data in ascending order


SELECT * FROM employees ORDER BY last_name;

-- Sorting data in descending order


SELECT * FROM employees ORDER BY hire_date DESC;

-- Limiting the number of rows returned


SELECT * FROM employees LIMIT 10;

-- Limiting the number of rows with an offset


SELECT * FROM employees LIMIT 10 OFFSET 20;

c) Displaying data from multiple tables (JOIN).

-- Inner Join
SELECT orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;
-- Left Join
SELECT employees.first_name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;

d) Aggregating data using group function.

-- Calculate the total salary for each department


SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;

-- Calculate the average salary


SELECT AVG(salary) AS average_salary
FROM employees;

e) Manipulating data (INSERT, UPDATE, DELETE):

-- Inserting a new record


INSERT INTO employees (first_name, last_name, salary)
VALUES ('John', 'Doe', 60000);

-- Updating an existing record


UPDATE employees
SET salary = 65000
WHERE employee_id = 101;

-- Deleting a record
DELETE FROM employees
WHERE employee_id = 102;

f) Creating and managing tables:

-- Creating a new table


CREATE TABLE products (
product_id INT PRIMARY KEY,
product_nameVARCHAR(255),
price DECIMAL(10, 2)
);

-- Modifying a table (adding a new column)


ALTER TABLE employees
ADD COLUMN email VARCHAR(255);

-- Dropping a table
DROP TABLE products;
Experiment No: - 4

ProgramName: Normalization

TheoryConcept:

Normalization is a database design process used to organize data in a relational database


efficiently and reduce data redundancy. It is a multi-step process that sets the data into tabular form and
removes the duplicated data from the relational tables.Normalization typically involves dividing a
database into two or more tables and defining relationships between them. Let's go through an example of
normalizing a database with sample data and MySQL queries. We'll start with an unnormalized table and
normalize it step by step.

Step 1: Create an Unnormalized Table


Suppose we have a table called "CustomerOrders" that stores information about customers and their
orders. This table is not normalized because it contains repeating groups and data redundancy:

CREATE TABLE CustomerOrders (


customer_id INT PRIMARY KEY,
customer_nameVARCHAR(255),
order_id INT,
order_date DATE,
total_amountDECIMAL(10, 2)
);

INSERT INTO CustomerOrders (customer_id, customer_name, order_id, order_date, total_amount)


VALUES
(1, 'Alice', 101, '2023-01-15', 100.00),
(1, 'Alice', 102, '2023-02-20', 150.00),
(2, 'Bob', 201, '2023-03-10', 75.50),
(3, 'Charlie', 301, '2023-04-05', 200.00);

Step 2: Normalize the Data

We'll normalize the data by creating two separate tables: "Customers" and "Orders." The"Customers"
table will store customer information, and the "Orders" table will store order information.

-- Create the Customers table


CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
customer_nameVARCHAR(255)
);

-- Create the Orders table


CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amountDECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

-- Populate the Customers table with unique customer information


INSERT INTO Customers (customer_id, customer_name)
SELECT DISTINCT customer_id, customer_name FROM CustomerOrders;

-- Populate the Orders table with order information


INSERT INTO Orders (order_id, customer_id, order_date, total_amount)
SELECT order_id, customer_id, order_date, total_amount FROM CustomerOrders;

Step 3: Query the Normalized Tables

Now that we have normalized our data, we can query the "Customers" and "Orders" tables to
retrieve information:

-- Query to retrieve customer information


SELECT * FROM Customers;

-- Query to retrieve order information


SELECT * FROM Orders;

-- Query to retrieve customer names and their total order amounts


SELECT c.customer_name, SUM(o.total_amount) AS total_order_amount
FROM Customers c
JOIN Orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_name;

Output:

These queries demonstrate the result of normalizing the data. The "Customers" table contains
unique customer information, and the "Orders" table stores order details with a reference to the
customer. The last query retrieves the total order amount for each customer, demonstrating the power of
relational databases and normalization.
Experiment No-5

ProgramName: Creating cursor in MYSQL


TheoryConcept:In MySQL, Cursor can also be created. Following are the steps for creating a cursor.

Implementation:

1. Declare Cursor
A cursor is a select statement, defined in the declaration section in MySQL.
Syntax
1. DECLARE cursor_name CURSOR FOR
2. Select statement;
Parameter:
cursor_name: name of the cursor
select_statement: select query associated with the cursor

2.Open Cursor
After declaring the cursor the next step is to open the cursor using open statement.
Syntax
Open cursor_name;
Parameter:
cursor_name: name of the cursor which is already declared.

3. Fetch Cursor
After declaring and opening the cursor, the next step is to fetch the cursor. It is used to fetch the row or the
column.
Syntax
FETCH [ NEXT [ FROM ] ] cursor_name INTO variable_list;
Parameter:
cursor_name: name of the cursor
variable_list: variables, comma separated, etc. is stored in a cursor for the result set

4. Close Cursor
The final step is to close the cursor.
Syntax
Close cursor_name;
Parameter:
Cursor_name: name of the cursor
Experiment No -6
ProgramName:Creating procedure and functions in MYSQL

TheoryConcept:
Let us understand how to create a procedure in MySQL through example. First, we need to select a
database that will store the newly created procedure. We can select the database using the below
statement:

mysql> USE database_name;

Suppose this database has a table named student_info that contains the following data:

Implementation:

Procedure without Parameter


Suppose we want to display all records of this table whose marks are greater than 70 and count all the table
rows. The following code creates a procedure named get_merit_students:

1. DELIMITER &&
2. CREATE PROCEDURE get_merit_student ()
3. BEGIN
4. SELECT * FROM student_info WHERE marks > 70;
5. SELECT COUNT(stud_code) AS Total_Student FROM student_info;
6. END &&
7. DELIMITER ;

If this code executed successfully, we would get the below output:


Let us call the procedure to verify the output:
mysql> CALL get_merit_student();
It will give the output as follows:

What is a function in MySQL?


In MySQL, a function is a stored program that you can pass parameters into and then return a
value.

Create Function
Just as you can create functions in other languages, you can create your own functions in
MySQL. Let's take a closer look.

Syntax
The syntax to create a function in MySQL is:

function_name
The name to assign to this function in MySQL.
parameter

One or more parameters passed into the function. When creating a function, all parameters
are considered to be IN parameters (not OUT or INOUT parameters) where the parameters
can be referenced by the function but can not be overwritten by the function.
return_datatype
The data type of the function's return value.
declaration_section
The place in the function where you declare local variables.
executable_section
The place in the function where you enter the code for the function.

You could then reference your new function as follows:

SELECT CalcIncome (1000);

Drop Function
Once you have created your function in MySQL, you might find that you need to remove it from the
database.

Syntax
The syntax to a drop a function in MySQL is:
DROP FUNCTION [ IF EXISTS ]function_name;

function_name
The name of the function that you wish to drop.

Example
Let's look at an example of how to drop a function in MySQL.
For example:

DROP FUNCTION CalcIncome;

This example would drop the function called CalcIncome.


Experiment No-7

ProgramName:Creating packages and triggers


TheoryConcept:
We can create a new trigger in MySQL by using the CREATE TRIGGER statement. It is to ensure that
we have trigger privileges while using the CREATE TRIGGER command. The following is the basic
syntax to create a trigger:

Implementation:

Parameter Explanation
The create trigger syntax contains the following parameters:
trigger_name: It is the name of the trigger that we want to create. It must be written after the
CREATE TRIGGER statement. It is to make sure that the trigger name should be unique within the

schema.
trigger_time: It is the trigger action time, which should be either BEFORE or AFTER. It is the required
parameter while defining a trigger. It indicates that the trigger will be invoked before or after each row
modification occurs on the table.

trigger_event: It is the type of operation name that activates the trigger. It can be
either INSERT, UPDATE, or DELETE operation. The trigger can invoke only one event at one time. If
we want to define a trigger which is invoked by multiple events, it is required to define multiple triggers,
and one for each event.

table_name: It is the name of the table to which the trigger is associated. It must be written after the ON
keyword. If we did not specify the table name, a trigger would not exist.

BEGIN END Block: Finally, we will specify the statement for execution when the trigger is activated.
If we want to execute multiple statements, we will use the BEGIN END block that contains a set of
queries to define the logic for the trigger.
The trigger body can access the column's values, which are affected by the DML statement.
The NEW and OLD modifiers are used to distinguish the column values BEFORE and AFTER the
execution of the DML statement. We can use the column name with NEW and OLD modifiers
as OLD.col_name and NEW.col_name. The OLD.column_name indicates the column of an existing
row before the updation or deletion occurs. NEW.col_name indicates the column of a new row that will
be inserted or an existing row after it is updated.

For example, suppose we want to update the column name message_info using the trigger. In the
trigger body, we can access the column value before the update as OLD.message_info and the new
value NEW.message_info.
We can understand the availability of OLD and NEW modifiers with the below table:

MySQL Trigger Example


Let us start creating a trigger in MySQL that makes modifications in the employee table. First, we will create a

new table named employee by executing the below statement:


Next, execute the SELECT statement to verify the inserted record:
Next, we will create a BEFORE INSERT trigger. This trigger is invoked automatically insert the
working_hours = 0 if someone tries to insert working_hours< 0.

Creating
Packages:

Package Specification:
The specification is the interface to the package. It just DECLARES the types, variables, constants,
exceptions, cursors, and subprograms that can be referenced from outside the package. In other words, it
contains all information about the content of the package, but excludes the code for the subprograms.
All objects placed in the specification are called public objects. Any subprogram not in the package
specification but coded in the package body is called a private object.

The following program provides a more complete package. We will use the CUSTOMERS table stored
in our database with the following records –

When the above code is executed at the SQL prompt, it creates the above package and displays the
following result −Package created
The above example makes use of the nested table. We will discuss the concept of nested
table in the next chapter.
When the above code is executed at the SQL prompt, it produces the following result −

Package body created.

Using The Package


The following program uses the methods declared and defined in the package c_package.
ExperimentNo:8
Program Name:Design and implementation of payroll processing system

TheoryConcept:

1. Requirements Gathering:

Identify the specific requirements of your payroll system, including the types of employees, salary
structures, deductions, and reporting needs.

2. Database Design:

Create a MySQL database to store employee and payroll-related data. You can use tools like MySQL
Workbench for this task.

Define tables for:

Employees (employee_id, name, address, contact, etc.)

Salary Information (salary_id, employee_id, basic_salary, allowances, etc.)

Deductions (deduction_id, employee_id, type, amount, etc.)

Payroll Records (payroll_id, employee_id, pay_period, net_salary, etc.)

3. Establish Database Relationships:

Set up relationships between tables using foreign keys to ensure data integrity.

4. Data Input and Validation:

Develop a user interface for data input, which allows HR personnel to add, edit, and delete employee
records.

Implement data validation to ensure that the entered data is accurate and consistent.

5. Salary Calculation:

Write SQL queries or create stored procedures to calculate employee salaries based on the salary structure
and allowances.

6. Deduction Management:

Create functions or stored procedures to manage deductions, including tax deductions, insurance, and
other deductions.

7. Payroll Processing:

Implement a payroll processing module that generates payroll records for each employee based on the pay
period.
8. Reporting:

Design reports to generate payslips, payroll summaries, and tax reports.

9. Security:

Implement user authentication and authorization to restrict access to sensitive payroll data.

10. Testing:

Thoroughly test the system to ensure accuracy in salary calculations, data input, and report generation.

Implementation:

To implement a payroll processing system in MySQL, you'll need to create various tables to store employee
information, salary details, deductions, payroll records, and more. Below is an example of MySQL code to
create some of the essential tables for a basic payroll system. You can expand upon this schema to meet
your specific requirements:
MYSQL Code:

-- Create a database for the payroll system


CREATE DATABASE PayrollSystem;
USE PayrollSystem;

-- Create a table to store employee information


CREATE TABLE Employees (
employee_id INT AUTO_INCREMENT PRIMARY KEY,
first_nameVARCHAR(50),
last_nameVARCHAR(50),
email VARCHAR(100),
hire_date DATE,
address VARCHAR(255),
phone VARCHAR(15),
department VARCHAR(50),
job_titleVARCHAR(50),
salary DECIMAL(10, 2)
);

-- Create a table to store salary information


CREATE TABLE Salary (
salary_id INT AUTO_INCREMENT PRIMARY KEY,
employee_id INT,
basic_salaryDECIMAL(10, 2),
allowances DECIMAL(10, 2),
FOREIGN KEY (employee_id) REFERENCES Employees(employee_id)
);

-- Create a table to store deduction information


CREATE TABLE Deductions (
deduction_id INT AUTO_INCREMENT PRIMARY KEY,
employee_id INT,
deduction_typeVARCHAR(50),
amount DECIMAL(10, 2),
FOREIGN KEY (employee_id) REFERENCES Employees(employee_id)
);

-- Create a table to store payroll records


CREATE TABLE PayrollRecords (
payroll_id INT AUTO_INCREMENT PRIMARY KEY,
employee_id INT,
pay_period_start DATE,
pay_period_end DATE,
net_salaryDECIMAL(10, 2),
FOREIGN KEY (employee_id) REFERENCES Employees(employee_id)
);

In the code above:

 We create a database named "PayrollSystem" to contain all the tables.


 The "Employees" table stores basic employee information such as name, email, hire date, address, and
department.
 The "Salary" table stores salary-related information for each employee, including basic salary and
allowances. It has a foreign key relationship with the "Employees" table.
 The "Deductions" table stores various types of deductions for employees, like taxes and insurance. It
also has a foreign key relationship with the "Employees" table.
 The "PayrollRecords" table is used to store records of each payroll run, including the employee ID, pay
period start and end dates, and net salary. It has a foreign key relationship with the "Employees" table.
ExperimentNo: 9
ProgramName: Write a CURSOR to display list of clientsintheCLIENT_MASTERtable.

TheoryConcept:ThefollowingexamplewouldillustratetheconceptofCURSORS.Wewillbeusingthe
CLIENT_MASTER table and display records.

Implementation:

DECLARE
CURSOR
client_curisSELECTid,name
,address
FROM client_master;
client_recclient_cur%rowt
ype;BEGIN
OPENclient_cur;
LOOP
FETCH client_cur into
client_rec;EXITWHENclient_cur
%notfound;
DBMS_OUTPUT.put_line(client_rec.id||''||client_rec.name);
END LOOP;
END;
/
Output:Whenthe above codeis executed atSQLprompt,itproducesthefollowing result:
1 Ramesh
2 Khilan
3 kaushik
4 Chaitali
5 Hardik
6 Komal

PL/SQLprocedure successfully completed.


ExperimentNo: 10

ProgramName:CreatingEntity-RelationshipDiagramusingcasetools.

Theory Concept: Entity relationship diagram (ERD) is a kind of diagram for presenting visually
thestructure of relational database. In this experiment we will make use of ERD to model the
databasestructure of a simple bus route management system.

Implementation:
1. StartVisualParadigm.Selectanewworkspacefolderforthistutorial.
2. SelectProject>Newfromthetoolbartocreateaproject.NametheprojectasBusRouteMa
nagement and confirm.
3. TocreateanERD,selectDiagram>Newfromthetoolbar.IntheNewDiagramwindow,selectEntityRel
ationship Diagram and clickNext. Enter Bus Route Management as diagram name and click
OK.
4. Let's start by creating the first entity Route. Select Entity in diagram toolbar and click on the
diagram tocreatean entity. Name theentityRouteand press Enterto confirm.

5. CreatecolumnsinRoute.Let'sstartwithaprimarykey.RightclickonentityRouteandselectNewCol
umnfrom popup menu.

6. Enter+id:varchar(10)andpressEnter.Notethatthe+signmeansthatthecolumnisaprimarykey.Varc
haris the columntype and 10 isthe length.

7. Enterfare:floatandpressEnter, thenEsctocreateanothercolumn.

8. CreateentityStop.Abusroutehasmanybusstops,whileastopcanbesharedbymanyroutes.Therefore,there
is a many-to-many relationship between Route and Stop. Place the mouse pointer over
theRouteentity.DragouttheResourceCatalogiconattopright.
9. Release the mouse button and select Many-to-Many Relationship -> Entity from Resource Catalog.

NamethenewentityStop,YoucanseethatalinkedentityRoute_Stopisautomaticallycreatedinbetwee
n Route and Stop, with foreign key added.

10. Create the following columns in Stop:

K Nam Type
e e
y
P id int(10)
K
name varchar(2
55)
termi blob
nus
11. 11.
The diagram should now become:

12. A route has multiple bus schedules. Create an entity Schedule from Route with a one-to-
manyrelationship.MovethemousepointertoRoute.PressanddragouttheResourceCatalogicon.
Select One-to-Many Relationship -> Entity to create entity Schedule.

13. Create the following columns in Schedule:

Key Name Type

PK id int(10)

departure Date

arrive Date

14. A schedule is handled by a bus. Create an entity Bus from Schedule, with an one-to-one
relationship.Create the following columns inBus:

Key Name Type

PK vehicle_id int(10)

fleet_id varchar(10)

last_main Date
15. The diagram should become:

16. A bus is driven by a bus driver. Create entity Driver from Bus with a one-to-one relationship. Add
thefollowing columns to Driver:

Key Name Type

PK Id int(10)

Name varchar(255)

employ_date Date

17. This is the final ERD.


ExperimentNo:11

ProgramName: PL/SQLprogramming
a. WriteaPL/SQLblockcodetoprintthesquaresofnumbersupto 99.
b. WriteaPL/SQLblockcodetoinsertdataintotableCUSTOMER

TheoryConcept:
Theprogramwouldprintthesquaresofnumbersupto99usingforloopanddataintotableCUSTOMERin
pl/sql.

Implementation:
Ans
(a):DECLARE

BEGIN

forxin1..99loop

dbms_output.put_l
ine(x*x);endloop;
end;
Output:
Implementation:

Ans:(b)
Null? Type

desc customer;Name
VARCHAR2(10)

C_IDVARCHAR2(2)CNAME
SALARY NUMBER

select*fromcustomer;

Output:
C_CNAME SALARY

c1jkjkjkj 7888

You might also like