0% found this document useful (0 votes)
15 views35 pages

DMBS lab 6 to 20

The document outlines a series of practical experiments focused on Database Management Systems (DBMS) and SQL, including the creation and manipulation of databases, tables, and views. It covers core concepts of DBMS, historical evolution, basic SQL commands, and PL/SQL programming for various operations such as inserting data, using cursors, and embedding PL/SQL in Java for banking transactions. Each experiment aims to enhance understanding of database operations and programming techniques in a structured manner.

Uploaded by

rirakik320
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views35 pages

DMBS lab 6 to 20

The document outlines a series of practical experiments focused on Database Management Systems (DBMS) and SQL, including the creation and manipulation of databases, tables, and views. It covers core concepts of DBMS, historical evolution, basic SQL commands, and PL/SQL programming for various operations such as inserting data, using cursors, and embedding PL/SQL in Java for banking transactions. Each experiment aims to enhance understanding of database operations and programming techniques in a structured manner.

Uploaded by

rirakik320
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Index

Seria Name of Program Date of Date of Grade Signature


l No. Assignment Submission

AI-DS(B1)
AI-DS(B1)
Practical 1: Introduction to Database
Management System (DBMS)
Aim: To comprehend the fundamental principles of Database Management Systems (DBMS)
and Structured Query Language (SQL), explore the historical development of DBMS, and
gain practical experience in creating and manipulating a basic database using SQL.

1. Introduction to Databases:
A Database is a systematically organized collection of data, typically stored and accessed
electronically from a computer system. Databases are designed to manage and organize
data in a structured format, enabling efficient storage, retrieval, and manipulation of
information. They serve as the backbone for various applications, ranging from customer
relationship management (CRM) systems to educational institutions' student information
systems.

2. SQL (Structured Query Language):


SQL is the standard programming language used to manage and manipulate relational
databases. It enables users to perform a variety of tasks, including querying data, updating
records, inserting new data, and deleting data. SQL commands are categorized into different
subsets based on their functions:

DDL (Data Definition Language): Commands like CREATE, ALTER, and DROP are used to
define and modify the database schema.

DML (Data Manipulation Language): Commands like SELECT, INSERT, UPDATE, and
DELETE allow users to manipulate data within tables.

DCL (Data Control Language): GRANT and REVOKE commands manage user access and
permissions within the database.

TCL (Transaction Control Language): Commands like COMMIT, ROLLBACK, and


SAVEPOINT are used to manage transactions within the database.

3. Overview of Database Management Systems (DBMS):


A Database Management System (DBMS) is a sophisticated software application that
enables users to define, create, maintain, and control access to databases. It provides an
interface between the database and the users or application programs, ensuring that data is

AI-DS(B1)
consistently organized and remains easily accessible. Popular DBMS software includes
MySQL, Oracle, Microsoft SQL Server, PostgreSQL, and MongoDB, each offering unique
features to meet various data management needs.

4. Historical Evolution of DBMS:


1960s: The early concepts of databases emerged, with an emphasis on hierarchical and
network database models.

1970s: Edgar F. Codd introduced the relational database model, revolutionizing the field
and laying the groundwork for modern DBMS.

1980s-1990s: The development and commercialization of relational databases, such as


Oracle, DB2, and Microsoft SQL Server, dominated the industry.

2000s-Present: The rise of NoSQL databases, like MongoDB and Cassandra, addresses the
growing demand for handling large volumes of unstructured data in distributed computing
environments.

5. Core Concepts of DBMS:


Entity: Represents a real-world object or concept with distinct existence within the
database (e.g., Student, Course).

Attribute: A characteristic or property of an entity (e.g., Student ID, Student Name).

Relation: A table within a relational database, consisting of rows (records) and columns
(attributes).

Primary Key: A unique identifier for each record in a table, ensuring data integrity.

Foreign Key: A field in one table that uniquely identifies a row in another table,
establishing a relationship between the two tables.

6. Basic SQL Commands:


-- Creating a Database
CREATE DATABASE School;

-- Selecting the Database


USE School;

-- Creating a Table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT,
Major VARCHAR(50)

AI-DS(B1)
);

-- Inserting Data into the Table


INSERT INTO Students (StudentID, FirstName, LastName, Age, Major)
VALUES (1, 'Vishal', 'Chaurasia', 20, 'Computer Science');

-- Querying Data from the Table


SELECT * FROM Students;

-- Updating Data in the Table


UPDATE Students
SET Age = 21
WHERE StudentID = 1;

-- Deleting Data from the Table


DELETE FROM Students
WHERE StudentID = 1;

-- Dropping the Table


DROP TABLE Students;

-- Dropping the Database


DROP DATABASE School;

7. Conclusion:
This practical has provided an introductory exploration of databases, DBMS, and SQL, along
with an overview of their historical context. Mastering these foundational concepts is
essential for advancing in the field of database management and understanding the
intricacies of modern data systems.

AI-DS(B1)
Experiment– 6
Aim: To perform various operations on views using SQL on the EMPLOYEE table. This
includes:

1. Creating views with and without the CHECK OPTION.

2. Selecting data from a view.

3. Dropping views from the database.

Objective:

The objective of this experiment is to:

1. Understand the concept of views in relational databases and their importance in


simplifying complex queries.

2. Learn how to create views with constraints using the CHECK OPTION to ensure
data integrity.

3. Practice selecting data from views to retrieve specific records based on


predefined criteria.

4. Demonstrate how to drop views when they are no longer needed, freeing up
database resources.

Given Problem: -

1. Creating Views (With and Without Check Option)

 Create View without Check Option:

AI-DS(B1)
CREATE VIEW Employee_View AS

SELECT FNAME, LNAME, SEX, SALARY

FROM EMPLOYEE;

This query creates a simple view called Employee_View that shows the first name, last
name, sex, and salary of employees.

 Create View with Check Option:

CREATE VIEW High_Salary_View AS

SELECT FNAME, LNAME, SALARY

FROM EMPLOYEE

WHERE SALARY > 40000

WITH CHECK OPTION;

This creates a view called High_Salary_View, showing only employees with a salary
greater than 40,000. The WITH CHECK OPTION ensures that any future changes to the
base table through this view must satisfy the condition SALARY > 40000.

2. Selecting from a View

To select data from the view:

 Selecting from Employee_View:

SELECT * FROM Employee_View;

This will return the details of employees (first name, last name, sex, and salary) as per
the defined view.

 Selecting from High_Salary_View:

SELECT * FROM High_Salary_View;

SELECT * FROM High_Salary_View;

SELECT * FROM High_Salary_View;

This query will return details of employees whose salary is greater than 40,000.

3. Dropping Views

AI-DS(B1)
To drop a view when it is no longer needed, use the following syntax:

 Dropping Employee_View:

DROP VIEW Employee_View;

 Dropping High_Salary_View:

DROP VIEW High_Salary_View;

AI-DS(B1)
Experiment- 7
Aim:

To write a PL/SQL program using a FOR loop to:

1. Insert ten rows into a database table.

2. Print integers from 1 to 10 using the FOR loop.

Objective:

The objective of this experiment is to:

1. Understand the usage of loops in PL/SQL to automate repetitive tasks.

2. Learn how to insert multiple rows into a table using a loop.

3. Practice how to print integers using the FOR loop in PL/SQL.

Program:

-- Insert 10 Rows into a Database Table Using PL/SQL FOR Loop


-- Assume the table is named 'number_table' with one column 'num'
CREATE TABLE number_table (
num NUMBER
);

-- PL/SQL block to insert 10 rows into the 'number_table'


BEGIN
FOR i IN 1..10 LOOP
INSERT INTO number_table (num) VALUES (i);
END LOOP;

-- Commit the transaction to save the changes


COMMIT;
END;
/
Explanation:
 The table number_table has a single column num where we will insert integers
from 1 to 10.

AI-DS(B1)
 The FOR loop iterates through values from 1 to 10 and inserts them into the
number_table using the INSERT INTO statement.
 After inserting, the COMMIT statement ensures the changes are saved
permanently to the database.

-- PL/SQL block to print integers from 1 to 10


BEGIN
FOR i IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE('The value of i is: ' || i);
END LOOP;
END;
/
Explanation:
 This program simply prints integers from 1 to 10 using the FOR loop.
 The DBMS_OUTPUT.PUT_LINE procedure is used to print the current value of
i during each iteration of the loop.

Output: -
SELECT * FROM number_table;

num

AI-DS(B1)
6

10

Program 2
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5
The value of i is: 6
The value of i is: 7
The value of i is: 8
The value of i is: 9
The value of i is: 10

AI-DS(B1)
Experiment- 8
Aim:

To write a PL/SQL program using a cursor to retrieve and display the top five
highest-paid employees from the EMPLOYEE table.

Objective:

The objective of this experiment is to:

1. Understand how to declare and use cursors in PL/SQL to handle result sets.

2. Retrieve and display records for specific conditions using cursors.

3. Practice selecting the top 5 employees based on salary.

Program: Cursor to Select Top 5 Highest Paid Employees

-- Assume the EMPLOYEE table is already created with relevant fields

CREATE TABLE EMPLOYEE (

EmpNo NUMBER,

Name VARCHAR2(50),

Salary NUMBER,

Designation VARCHAR2(50),

DeptID NUMBER

);

-- Insert sample data into the EMPLOYEE table

INSERT INTO EMPLOYEE (EmpNo, Name, Salary, Designation, DeptID)

VALUES (1, 'John Doe', 60000, 'Manager', 101);

AI-DS(B1)
INSERT INTO EMPLOYEE (EmpNo, Name, Salary, Designation, DeptID)

VALUES (2, 'Jane Smith', 50000, 'Developer', 102);

INSERT INTO EMPLOYEE (EmpNo, Name, Salary, Designation, DeptID)

VALUES (3, 'Alice Brown', 75000, 'Senior Developer', 101);

INSERT INTO EMPLOYEE (EmpNo, Name, Salary, Designation, DeptID)

VALUES (4, 'Bob Martin', 45000, 'Tester', 103);

INSERT INTO EMPLOYEE (EmpNo, Name, Salary, Designation, DeptID)

VALUES (5, 'Charlie White', 85000, 'CTO', 101);

INSERT INTO EMPLOYEE (EmpNo, Name, Salary, Designation, DeptID)

VALUES (6, 'Emily Green', 72000, 'Project Manager', 102);

-- PL/SQL Block to use a cursor to retrieve the top 5 highest-paid employees

DECLARE

CURSOR emp_cursor IS

SELECT EmpNo, Name, Salary, Designation, DeptID

FROM EMPLOYEE

ORDER BY Salary DESC

FETCH FIRST 5 ROWS ONLY; -- Top 5 highest salaries

emp_record emp_cursor%ROWTYPE;

BEGIN

OPEN emp_cursor;

DBMS_OUTPUT.PUT_LINE('EmpNo | Name | Salary | Designation |


DeptID');

AI-DS(B1)
DBMS_OUTPUT.PUT_LINE('------------------------------------------------------------');

LOOP

FETCH emp_cursor INTO emp_record;

EXIT WHEN emp_cursor%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(emp_record.EmpNo || ' | ' || emp_record.Name || ' | '


||

emp_record.Salary || ' | ' || emp_record.Designation || ' | ' ||

emp_record.DeptID);

END LOOP;

CLOSE emp_cursor;

END;

Output: -

EmpNo | Name | Salary | Designation | DeptID

------------------------------------------------------------

5 | Charlie White | 85000 | CTO | 101

3 | Alice Brown | 75000 | Senior Developer | 101

6 | Emily Green | 72000 | Project Manager | 102

1 | John Doe | 60000 | Manager | 101

2 | Jane Smith | 50000 | Developer | 102

AI-DS(B1)
Experiment- 9
Aim:

To demonstrate how to embed PL/SQL in a high-level host language (such as C or


Java) to perform a banking debit transaction.

Objective:

The objective of this experiment is to:

1. Illustrate how to embed and execute PL/SQL blocks inside a high-level


programming language like Java.

2. Implement a banking debit transaction using PL/SQL in Java, simulating


account balance deduction.

3. Use the necessary Java Database Connectivity (JDBC) for interacting with a
database.

Program: Embedding PL/SQL in Java for a Debit Transaction

In this example, we demonstrate embedding PL/SQL into a Java program using


JDBC for executing a debit transaction from a bank account.

Banking Debit Transaction Logic:

 A BANK_ACCOUNT table will be used to simulate account information.

 A PL/SQL block will deduct a specified amount from the account balance if
sufficient funds exist.

Steps:

1. Create the Bank Account Table.

2. Write the PL/SQL block for Debit Transaction.

3. Embed the PL/SQL block in a Java Program.

Step 1: Create the Bank Account Table

CREATE TABLE BANK_ACCOUNT (

AI-DS(B1)
AccountNo NUMBER PRIMARY KEY,

Name VARCHAR2(50),

Balance NUMBER

);

-- Insert sample data

INSERT INTO BANK_ACCOUNT (AccountNo, Name, Balance) VALUES (1001, 'John


Doe', 5000);

INSERT INTO BANK_ACCOUNT (AccountNo, Name, Balance) VALUES (1002, 'Jane


Smith', 3000);

COMMIT;

Step 2: PL/SQL Block for Debit Transaction

This PL/SQL block will debit an account and check for sufficient balance before
deducting.

DECLARE

v_balance BANK_ACCOUNT.Balance%TYPE;

BEGIN

-- Fetch current balance

SELECT Balance INTO v_balance FROM BANK_ACCOUNT WHERE AccountNo =


1001;

IF v_balance >= 1000 THEN

-- If sufficient balance, deduct the amount

UPDATE BANK_ACCOUNT

SET Balance = Balance - 1000

WHERE AccountNo = 1001;

AI-DS(B1)
DBMS_OUTPUT.PUT_LINE('Debit transaction successful. Amount deducted:
1000');

ELSE

DBMS_OUTPUT.PUT_LINE('Insufficient balance.');

END IF;

COMMIT;

END;

Step 3: Embedding PL/SQL in Java using JDBC

Here, the Java program connects to the database and executes the PL/SQL block to
perform the debit transaction.

import java.sql.*;

public class BankTransaction {

public static void main(String[] args) {

Connection conn = null;

CallableStatement stmt = null;

try {

// Load and register Oracle JDBC Driver (or any other DB driver)

Class.forName("oracle.jdbc.driver.OracleDriver");

// Establish connection to the database

AI-DS(B1)
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"username", "password");

// PL/SQL block for debit transaction

String plsqlBlock = "{ DECLARE "

+ " v_balance BANK_ACCOUNT.Balance%TYPE; "

+ "BEGIN "

+ " SELECT Balance INTO v_balance FROM BANK_ACCOUNT WHERE


AccountNo = 1001; "

+ " IF v_balance >= 1000 THEN "

+ " UPDATE BANK_ACCOUNT SET Balance = Balance - 1000


WHERE AccountNo = 1001; "

+ " DBMS_OUTPUT.PUT_LINE('Debit transaction successful.


Amount deducted: 1000'); "

+ " ELSE "

+" DBMS_OUTPUT.PUT_LINE('Insufficient balance.'); "

+ " END IF; "

+ " COMMIT; "

+ "END; }";

// Prepare and execute the PL/SQL block

stmt = conn.prepareCall(plsqlBlock);

stmt.execute();

System.out.println("Transaction executed successfully!");

AI-DS(B1)
} catch (Exception e) {

e.printStackTrace();

} finally {

// Clean up the environment

try {

if (stmt != null) stmt.close();

if (conn != null) conn.close();

} catch (SQLException se) {

se.printStackTrace();

Output:

When the program is run, if AccountNo = 1001 has sufficient balance, the output
would be:

Transaction executed successfully!

Debit transaction successful. Amount deducted: 1000

If there is insufficient balance, the output would be:

Transaction executed successfully!

Insufficient balance.

AI-DS(B1)
Experiment- 10
Aim:

To write a PL/SQL procedure that inserts a tuple consisting of an integer i and a


string 'xxx' into a given relation.

Objective:

The objective of this experiment is to demonstrate how to create and execute a


PL/SQL procedure that inserts values into a table dynamically, using an input
integer i and a fixed string 'xxx'. The procedure will use SQL INSERT command
within the PL/SQL block to insert the tuple into the relation.

Example Table: TEST_TABLE

ID NAME

1 abc

2 def

PL/SQL Procedure:

CREATE OR REPLACE PROCEDURE insert_tuple(i IN NUMBER) IS

BEGIN

-- Insert a tuple into the given table

INSERT INTO TEST_TABLE (ID, NAME) VALUES (i, 'xxx');

-- Commit the transaction to save the changes

COMMIT;

-- Output message

DBMS_OUTPUT.PUT_LINE('Tuple (' || i || ', ''xxx'') inserted successfully.');

END;

AI-DS(B1)
Execution:

BEGIN

insert_tuple(5); -- Calls the procedure with i = 5

END;

Output:

When the procedure is executed with the input i = 5, it inserts the tuple (5, 'xxx')
into the TEST_TABLE. The output will be:

Tuple (5, 'xxx') inserted successfully.

Query to Check the Table:

SELECT * FROM TEST_TABLE;

Output:

ID NAME

1 abc

2 def

5 xxx

AI-DS(B1)
Experiment 11: Hello World Program
Aim:
To write a PL/SQL block to print "Hello World".

Objective:
To demonstrate the basic structure of a PL/SQL program and how to output a
simple message.

Code:

BEGIN

DBMS_OUTPUT.PUT_LINE('Hello World');

END;

Output:

Hello World

AI-DS(B1)
Experiment 12: Program to Add Two
Numbers
Aim:
To write a PL/SQL program to add two numbers and display the result.

Objective:
To demonstrate how to perform arithmetic operations in PL/SQL.

Code:

DECLARE

num1 NUMBER := 10;

num2 NUMBER := 20;

sum NUMBER;

BEGIN

sum := num1 + num2;

DBMS_OUTPUT.PUT_LINE('Sum = ' || sum);

END;

Output:

Sum = 30

AI-DS(B1)
Experiment 13: Program to Check Even
or Odd
Aim:
To write a PL/SQL program to check whether a number is even or odd.

Objective:
To demonstrate conditional statements in PL/SQL.

Code:

DECLARE

num NUMBER := 5;

BEGIN

IF MOD(num, 2) = 0 THEN

DBMS_OUTPUT.PUT_LINE(num || ' is Even');

ELSE

DBMS_OUTPUT.PUT_LINE(num || ' is Odd');

END IF;

END;

Output:

5 is Odd

AI-DS(B1)
Experiment 14: Program to Find
Factorial of a Number
Aim:
To write a PL/SQL program to find the factorial of a given number.

Objective:
To demonstrate the use of loops in PL/SQL.

Code:

DECLARE

num NUMBER := 5;

fact NUMBER := 1;

BEGIN

FOR i IN 1..num LOOP

fact := fact * i;

END LOOP;

DBMS_OUTPUT.PUT_LINE('Factorial = ' || fact);

END;

Output:

Factorial = 120

AI-DS(B1)
Experiment 15: Program to Reverse a
String
Aim:
To write a PL/SQL program to reverse a given string.

Objective:
To manipulate strings using PL/SQL.

Code:

DECLARE

str VARCHAR2(100) := 'PLSQL';

rev_str VARCHAR2(100) := '';

BEGIN

FOR i IN REVERSE 1..LENGTH(str) LOOP

rev_str := rev_str || SUBSTR(str, i, 1);

END LOOP;

DBMS_OUTPUT.PUT_LINE('Reversed String = ' || rev_str);

END;

Output:

Reversed String = LSQLP

AI-DS(B1)
Experiment 16: Display First 10 Natural
Numbers Using a Loop
Aim:
To write a PL/SQL program to display the first 10 natural numbers using a loop.

Objective:
To demonstrate loops in PL/SQL.

Code:

BEGIN

FOR i IN 1..10 LOOP

DBMS_OUTPUT.PUT_LINE(i);

END LOOP;

END;

Output:

10

AI-DS(B1)
Experiment 17: Program to Find
Maximum of Two Numbers
Aim:
To write a PL/SQL program to find the maximum of two numbers.

Objective:
To demonstrate conditional comparisons in PL/SQL.

Code:

DECLARE

num1 NUMBER := 15;

num2 NUMBER := 20;

BEGIN

IF num1 > num2 THEN

DBMS_OUTPUT.PUT_LINE('Max = ' || num1);

ELSE

DBMS_OUTPUT.PUT_LINE('Max = ' || num2);

END IF;

END;

Output:

Max = 20

AI-DS(B1)
Experiment 18: Check if a String is a
Palindrome
Aim:
To write a PL/SQL program to check if a string is a palindrome.

Objective:
To manipulate and compare strings in PL/SQL.

Code:

DECLARE

str VARCHAR2(100) := 'MADAM';

rev_str VARCHAR2(100) := '';

BEGIN

FOR i IN REVERSE 1..LENGTH(str) LOOP

rev_str := rev_str || SUBSTR(str, i, 1);

END LOOP;

IF str = rev_str THEN

DBMS_OUTPUT.PUT_LINE(str || ' is a palindrome');

ELSE

DBMS_OUTPUT.PUT_LINE(str || ' is not a palindrome');

END IF;

END;

Output:

MADAM is a palindrome

AI-DS(B1)
Experiment 19: Program to Calculate
Fibonacci Series
Aim:
To write a PL/SQL program to generate the Fibonacci series up to a given number of
terms.

Objective:
To demonstrate recursion and sequence generation in PL/SQL.

Code:

DECLARE

num1 NUMBER := 0;

num2 NUMBER := 1;

num3 NUMBER;

n NUMBER := 10; -- Number of terms

BEGIN

DBMS_OUTPUT.PUT_LINE(num1);

DBMS_OUTPUT.PUT_LINE(num2);

FOR i IN 3..n LOOP

num3 := num1 + num2;

DBMS_OUTPUT.PUT_LINE(num3);

num1 := num2;

num2 := num3;

END LOOP;

END;

AI-DS(B1)
Output:

13

21

34

AI-DS(B1)
Experiment 20: Check if a Number is an
Armstrong Number
Aim:
To write a PL/SQL program to check if a given number is an Armstrong number.

Objective:
To implement mathematical logic in PL/SQL to check if the sum of the cubes of the
digits of a number is equal to the number itself.

Code:

DECLARE

num NUMBER := 153;

temp NUMBER;

digit NUMBER;

sum NUMBER := 0;

BEGIN

temp := num;

WHILE temp > 0 LOOP

digit := MOD(temp, 10);

sum := sum + POWER(digit, 3);

temp := FLOOR(temp / 10);

END LOOP;

IF sum = num THEN

DBMS_OUTPUT.PUT_LINE(num || ' is an Armstrong number');

ELSE

AI-DS(B1)
DBMS_OUTPUT.PUT_LINE(num || ' is not an Armstrong number');

END IF;

END;

Output:

153 is an Armstrong number

AI-DS(B1)
AI-DS(B1)
AI-DS(B1)

You might also like