0% found this document useful (0 votes)
13 views33 pages

Dbms Laboratory Mannual (Final)

The DBMS Laboratory Manual outlines a series of experiments aimed at teaching SQL and database management concepts, including creating tables, using constraints, executing queries, and implementing joins. It also covers advanced topics like user-defined functions, stored procedures, triggers, and XML databases. Each experiment includes specific aims, SQL queries, and results demonstrating successful execution of database operations.

Uploaded by

121sudhan
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)
13 views33 pages

Dbms Laboratory Mannual (Final)

The DBMS Laboratory Manual outlines a series of experiments aimed at teaching SQL and database management concepts, including creating tables, using constraints, executing queries, and implementing joins. It also covers advanced topics like user-defined functions, stored procedures, triggers, and XML databases. Each experiment includes specific aims, SQL queries, and results demonstrating successful execution of database operations.

Uploaded by

121sudhan
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/ 33

DBMS LABORATORY MANNUAL

REGULATION 2021

WRITE EVERYTHING...
DBMS LABORATORY MANNUAL
LIST OF EXPERIMENTS:

1. Create a database table, add constraints (primary key, unique, check, not null), insert
rows, update, and delete rows using SQL DDL and DML commands.

2. Create a set of tables, add foreign key constraints and incorporate referential
integrity.

3. Query the database tables using different ‘where’ clause conditions and also
implement aggregate functions.

4. Query the database tables and explore sub queries and simple join operations.

5. Query the database tables and explore natural, equip and outer joins.

6. Write user defined functions and stored procedures in SQL.

7. Execute complex transactions and realize DCL and TCL commands.

8. Write SQL Triggers for insert, delete, and update operations in a database table.

9. Create View and index for database tables with many records.

10. Create an XML database and validate it using XML schema.

11. Create Document, column and graph-based data using NOSQL database tools.

12. Develop a simple GUI based database application and incorporate all the above-
mentioned features

13. Case Study using any of the real-life database applications from the following list
a) Inventory Management for a EMart Grocery Shop
b) Society Financial Management
c) Cop Friendly App – Eseva
d) Property Management – Email
e) Star Small and Medium Banking and Finance ● Build Entity Model diagram.
EXPERIMENT 1

AIM:

To create a database table, add constraints (primary key, unique, check, not null),
insert rows, update, and delete rows using SQL DDL and DML commands.

QUIERIES:

create table students (


id int ;
name varchar(20) ;
age int ;
constraint students_pk primary key (id) ;

Insert into students (id, name, age) values (‘1.’, ‘ABC’, ‘90’);
Insert into students (id, name, age) values (‘2.’, ‘DEF’, ‘91’);
Insert into students (id, name, age) values (‘3.’, ‘GHI’, ‘92’);
Insert into students (id, name, age) values (‘4.’, ‘JKL’, ‘93’);

Select * from students;

Alter table students add constraint name_uni unique (name);

Alter table students modify name varchar(25) not null;

Delete from students where name = ‘ABC’;

Select * from students;


RESULT:

Thus the database table with constraints and row operations have been
successfully executed.
EXPERIMENT 2

AIM:

To create a set of tables, add foreign key constraints and incorporate referential
integrity.

QUIERIES:

CREATE TABLE Customers (


customer_id INT PRIMARY KEY,
customer_nameVARCHAR(50),
customer_emailVARCHAR(50)
);

CREATE TABLE Orders (


order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

CREATE TABLE OrderItems (


order_id INT,
item_id INT,
quantity INT,
PRIMARY KEY (order_id, item_id),
FOREIGN KEY (order_id) REFERENCES Orders(order_id)
);

CREATE TABLE Items (


item_id INT PRIMARY KEY,
item_nameVARCHAR(50),
item_priceDECIMAL(10, 2)
);

ALTER TABLE Orders


ADD CONSTRAINT fk_customer_id
FOREIGN KEY (customer_id)
REFERENCES Customers(customer_id);

ALTER TABLE OrderItems


ADD CONSTRAINT fk_order_id
FOREIGN KEY (order_id)
REFERENCES Orders(order_id);

ALTER TABLE OrderItems


ADD CONSTRAINT fk_item_id
FOREIGN KEY (item_id)
REFERENCES Items(item_id);

INSERT INTO Customers (customer_id, customer_name, customer_email)


VALUES
(1, 'John Doe', 'johndoe@example.com'),
(2, 'Jane Smith', 'janesmith@example.com'),
(3, 'Bob Johnson', 'bjohnson@example.com');

INSERT INTO Items (item_id, item_name, item_price) VALUES


(1, 'Widget', 9.99),
(2, 'Gadget', 14.99),
(3, 'Thingamabob', 19.99);

INSERT INTO Orders (order_id, customer_id, order_date) VALUES


(1, 1, '2022-01-01'),
(2, 1, '2022-02-15'),
(3, 2, '2022-03-23');

INSERT INTO OrderItems (order_id, item_id, quantity) VALUES


(1, 1, 2),
(1, 2, 1),
(2, 3, 3),
(3, 2, 2),
(3, 3, 1);

SELECT * FROM customers WHERE customer_id = 1;


SELECT * FROM orders WHERE customer_id = 1;

RESULT:

Thus the set of tables with foreign key constraints and referential integrity have
been successfully executed.
EXPERIMENT 3

AIM:

To query the database tables using different ‘where’ clause conditions and also
implement aggregate functions.

QUIERIES:

CREATE TABLE employees (


id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT NOT NULL,
salary DECIMAL(10, 2) NOT NULL
);

INSERT INTO employees (id, name, age, salary)


VALUES (1, 'John', 30, 60000),
(2, 'Jane', 28, 55000),
(3, 'Bob', 35, 75000),
(4, 'Alice', 26, 50000),
(5, 'Mike', 42, 90000);

SELECT name, salary FROM employees


WHERE salary >50000;

SELECT MAX(salary) AS max_salary, MIN(salary) AS min_salary FROM


employees;
SELECT AVG(age) AS avg_age, MAX(age) AS max_age, MIN(age) AS
min_age FROM employees;

RESULT:
Thus the database using where conditions was successfully executed.
EXPERIMENT 4

AIM:

To query the database tables and explore sub queries and simple join operations.

QUEIRES:

CREATE TABLE customers (


customer_id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50),
phone VARCHAR(20)
);

INSERT INTO customers (customer_id, name, email, phone) VALUES


(1, 'John Doe', 'john.doe@example.com', '555-1234'),
(2, 'Jane Smith', 'jane.smith@example.com', '555-5678'),
(3, 'Bob Johnson', 'bob.johnson@example.com', '555-9012');

CREATE TABLE orders (


order_id INT PRIMARY KEY,
customer_id INT,
total DECIMAL(10,2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

INSERT INTO orders (order_id, customer_id, total) VALUES


(1, 1, 50.00),
(2, 2, 100.00),
(3, 1, 75.00),
(4, 3, 125.00);

SELECT customers.name, orders.total FROM customers JOIN orders ON


customers.customer_id = orders.customer_id WHERE orders.total> 75.00;
SELECT orders.order_id, customers.name, orders.total
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;

SELECT employees.name, departments.department_name


FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;

SELECT employees.name, departments.department_name


FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;
SELECT employees.name, departments.department_name
FROM employees
FULL OUTER JOIN departments
ON employees.department_id = departments.department_id;

RESULT:

Thus the database table with sub queries and simple joins were successfully
executed.
EXPERIMENT 5

AIM:

To query the database tables and explore natural, equip and outer joins.

QUEIRES:

CREATE TABLE customers (


customer_id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50),
phone VARCHAR(20)
);

INSERT INTO customers (customer_id, name, email, phone) VALUES


(1, 'John Doe', 'john.doe@example.com', '555-1234'),
(2, 'Jane Smith', 'jane.smith@example.com', '555-5678'),
(3, 'Bob Johnson', 'bob.johnson@example.com', '555-9012');

CREATE TABLE orders (


order_id INT PRIMARY KEY,
customer_id INT,
total DECIMAL(10,2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

INSERT INTO orders (order_id, customer_id, total) VALUES


(1, 1, 50.00),
(2, 2, 100.00),
(3, 1, 75.00),
(4, 3, 125.00);

SELECT *
FROM orders
NATURAL JOIN customers;
SELECT emp_name, salary, dept_name
FROM employees, departments
WHERE employees.dept_id = departments.dept_id;

SELECT *
FROM students
FULL OUTER JOIN courses
ON students.course_id = courses.course_id;

RESULT:

Thus the database table with natural, equi - and outer join has been successfully
explored.
EXPERIMENT 6

AIM:

To write user defined functions and stored procedures in SQL

QUEIRES:

User defined functions:


-- This function takes in two integers and returns their sum:

CREATE FUNCTION add_numbers(@num1 INT, @num2 INT)


RETURNS INT
AS
BEGIN
DECLARE @result INT
SET @result = @num1 + @num2
RETURN @result
END

-- Example usage:

SELECT dbo.add_numbers(3, 5)

-- Output:

Stored procedures:
-- This stored procedure takes in a customer ID and returns their name
and order history:

CREATE PROCEDURE get_customer_order_history


@customer_id INT
AS
BEGIN
SELECT name FROM customers WHERE id = @customer_id

SELECT order_date, product_name, quantity


FROM orders
WHERE customer_id = @customer_id
END

-- Example usage:
EXEC get_customer_order_history @customer_id = 1234

-- Output:

-- Name: John Smith


-- Order History:
-- - 2022-01-01: Widget 1, 10
-- - 2022-02-01: Widget 2, 5

RESULT:

Thus the User defined functions and stored procedures in SQL were successfully
executed.
EXPERIMENT 7

AIM:

To execute complex transactions and realize DCL and TCL commands.

QUEIRES:

To create a new user in the database, you can use the following DCL
command:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY


'password';

To grant privileges to the new user, you can use the following DCL
command:

GRANT ALL PRIVILEGES ON example_db.* TO


'newuser'@'localhost';

Now, let's say you want to create a new table in the database. You can use
the following TCL command:

USE example_db;
CREATE TABLE example_table (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
age INT(11) NOT NULL,
PRIMARY KEY (id)
);

To insert data into the new table, you can use the following TCL
command:

INSERT INTO example_table (name, age) VALUES ('John', 25),


('Jane', 30);

To select data from the new table, you can use the following TCL
command:

SELECT * FROM example_table;


RESULT:

Thus the Execution of complex transactions and realize DCL and TCL
commands was done successfully.
EXPERIMENT 8

AIM:

To write SQL Triggers for insert, delete, and update operations in a database
table.

QUEIRES:

CREATE TABLE employees (


id INT(11) NOT NULL AUTO_INCREMENT,
first_nameVARCHAR(50) NOT NULL,
last_nameVARCHAR(50) NOT NULL,
age INT(11) NOT NULL,
salary INT(11) NOT NULL,
PRIMARY KEY (id)
);

Insert Trigger:

CREATE TRIGGER employees_insert_trigger


AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit (action, employee_id, first_name,
last_name, age, salary)
VALUES ('INSERT', NEW.id, NEW.first_name, NEW.last_name,
NEW.age, NEW.salary);
END;

Delete trigger:

CREATE TRIGGER employees_delete_trigger


AFTER DELETE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit (action, employee_id, first_name,
last_name, age, salary)
VALUES ('DELETE', OLD.id, OLD.first_name, OLD.last_name,
OLD.age, OLD.salary);
END;

Update Trigger:
CREATE TRIGGER employees_update_trigger
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit (action, employee_id, first_name,
last_name, age, salary)
VALUES ('UPDATE', NEW.id, NEW.first_name,
NEW.last_name, NEW.age, NEW.salary);
END;

INSERT INTO employees (first_name, last_name, age, salary)


VALUES ('John', 'Doe', 25, 50000), ('Jane', 'Smith', 30, 60000);

SELECT * FROM employee_audit;

RESULT:

Thus the SQL Triggers for insert, delete, and update operations in a database
table were executed successfully.
EXPERIMENT 9

AIM:

To create View and index for database tables with a large number of records.

QUEIRES:

CREATE VIEW monthly_sales AS


SELECT YEAR(date) AS year, MONTH(date) AS month, SUM(quantity
* price) AS total_sales
FROM sales
GROUP BY YEAR(date), MONTH(date);

Index Creation:

CREATE INDEX idx_sales_customer ON sales (customer_id);

SELECT * FROM monthly_sales;

Assuming the “sales” database has the following values:


SELECT * FROM sales WHERE customer_id = 123;

RESULT:

Thus the View and index for database tables with a large number of records were
successfully executed.
EXPERIMENT 10

AIM:

To create an XML database and validate it using XML schema.

QUEIRES:

Let's assume we want to create a database of books. Each book will have
a title, author, publication year, and ISBN. Here's an example XML file
that contains information on three books:

<?xml version="1.0" encoding="UTF-8"?>


<books>
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
<isbn>9780141182636</isbn>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<year>1960</year>
<isbn>9780446310789</isbn>
</book>
<book>
<title>1984</title>
<author>George Orwell</author>
<year>1949</year>
<isbn>9780451524935</isbn>
</book>
</books>

Now that we have our XML database, we can create an XML schema to
validate it. An XML schema is a document that defines the structure,
content, and data types of an XML document. Here's an example XML
schema that we can use to validate our books database:

<?xml version="1.0" encoding="UTF-8"?>


<xs:schemaxmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="books">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="year" type="xs:integer"/>
<xs:element name="isbn" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

To validate our XML database against this schema, we can use an XML
validation tool like xmllint. Here's how to do it in the command line:

$ xmllint --noout --schema books.xsd books.xml


books.xml validates

RESULT:

Thus the XML database and validate it using XML schema were successfully
executed.
EXPERIMENT 11

AIM:

Tocreate Document, column and graph-based data using NOSQL database tools.

QUEIRES:

To demonstrate, we'll use three different NoSQL databases: MongoDB


for document-based data, Cassandra for column-based data, and Neo4j
for graph-based data.

Document-Based Data with MongoDB:

// Connect to MongoDB
constMongoClient = require('mongodb').MongoClient;
consturi = "mongodb+srv://<username>:<password>@<cluster-
address>/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("books");

// Insert a document
collection.insertOne({
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
isbn: "9780141182636"
}, function(err, result) {
console.log("Inserted document");
client.close();
});
});

Column-Based Data with Cassandra:

// Connect to Cassandra
constcassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['localhost'],
localDataCenter: 'datacenter1', keyspace: 'mykeyspace' });
client.connect(function(err, result) {
if(err) {
console.log('Error connecting to Cassandra:', err);
} else {
console.log('Connected to Cassandra');
// Create a table
const query = "CREATE TABLE books (id uuid PRIMARY KEY,
title text, author text, year int, isbn text)";
client.execute(query, function(err, result) {
if(err) {
console.log('Error creating table:', err);
} else {
console.log('Created table');
// Insert data into the table
const query = "INSERT INTO books (id, title, author, year, isbn)
VALUES (?, ?, ?, ?, ?)";
const params = [cassandra.types.Uuid.random(), "The Great
Gatsby", "F. Scott Fitzgerald", 1925, "9780141182636"];
client.execute(query, params, function(err, result) {
if(err) {
console.log('Error inserting data:', err);
} else {
console.log('Inserted data');
client.shutdown();
}
});
}
});
}
});

Graph data with Neo4j:

CREATE (:Person {name: 'John'})-[:FRIENDS_WITH]->(:Person


{name: 'Jane'}),
(:Person {name: 'John'})-[:FRIENDS_WITH]->(:Person {name:
'Jak'}),
(:Person {name: 'Jane'})-[:FRIENDS_WITH]->(:Person {name:
'Mary'}),
(:Person {name: 'Mary'})-[:FRIENDS_WITH]->(:Person {name:
'Jack'});

Once the query has finished executing, you can run a simple query
to retrieve all of the people in the graph:

MATCH (p:Person) RETURN p;


Output:
╒════════════════════════════════════════════════════════════════════════════════╕
│p │
╞════════════════════════════════════════════════════════════════════════════════╡
│ {name: 'John'} │
├──────────────────────────────────────────────────────────────────────────────────┤
│ {name: 'Jane'} │
├──────────────────────────────────────────────────────────────────────────────────┤
│ {name: 'Jack'} │
├──────────────────────────────────────────────────────────────────────────────────┤
│ {name: 'Mary'} │
╘════════════════════════════════════════════════════════════════════════════════╝

Finally, we can run a more complex query to retrieve all of the


friends of a specific person. For example, to find all of the friends
of John, we can run the following query:

MATCH (p:Person {name: 'John'})-[:FRIENDS_WITH]-


>(f:Person) RETURN f;

Output:
╒════════════════════════════════════════════════════════════════════════════════╕
│f │
╞════════════════════════════════════════════════════════════════════════════════╝

RESULT:

Thus the Document, column and graph-based data using NOSQL database
tools were successfully executed.
EXPERIMENT 12

AIM:

To develop a simple GUI based database application and incorporate all the
above-mentioned features.

QUEIRES:

First, we need to install the following libraries:


 tkinter: This is a standard GUI library for Python and is
used to create the graphical user interface.

 neo4j: This is a Python driver for Neo4j, which allows us to


interact with our graph database.

Once you have installed the required libraries, you can proceed with the
following steps:

 First, we will create a simple GUI that allows the user to enter the
details of a person and add them to the graph database. We will use
a Tkinter form with input fields for the person's name, age, and
gender.

import tkinter as tk
from neo4j import GraphDatabase

class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()

def create_widgets(self):
self.name_label = tk.Label(self, text="Name:")
self.name_label.pack(side="left")
self.name_entry = tk.Entry(self)
self.name_entry.pack(side="left")

self.age_label = tk.Label(self, text="Age:")


self.age_label.pack(side="left")
self.age_entry = tk.Entry(self)
self.age_entry.pack(side="left")
self.gender_label = tk.Label(self, text="Gender:")
self.gender_label.pack(side="left")
self.gender_entry = tk.Entry(self)
self.gender_entry.pack(side="left")

self.add_button = tk.Button(self, text="Add Person",


command=self.add_person)
self.add_button.pack(side="left")

def add_person(self):
name = self.name_entry.get()
age = int(self.age_entry.get())
gender = self.gender_entry.get()

# Create a Neo4j session


uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("neo4j", "password"))
session = driver.session()

# Add the person to the database


session.run("CREATE (:Person {name: $name, age: $age, gender:
$gender})", name=name, age=age, gender=gender)

# Close the session


session.close()

# Clear the input fields


self.name_entry.delete(0, tk.END)
self.age_entry.delete(0, tk.END)
self.gender_entry.delete(0, tk.END)

root = tk.Tk()
app = Application(master=root)
app.mainloop()

 The above code creates a simple GUI form with input fields for the
person's name, age, and gender. It also includes a button that, when
clicked, adds the person to the graph database using the Neo4j
driver.

 Next, we will create a feature that allows the user to view all the
people in the database. We will create a new button that, when
clicked, retrieves all the people from the database and displays
them in a new window:

class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()

def create_widgets(self):
self.name_label = tk.Label(self, text="Name:")
self.name_label.pack(side="left")
self.name_entry = tk.Entry(self)
self.name_entry.pack(side="left")

self.age_label = tk.Label(self, text="Age:")

RESULT:

Thus the simple GUI based database application and incorporate all the above-
mentioned features was created and executed successfully.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy