DBMS Final Lab Manual
DBMS Final Lab Manual
Reg.No : Semester :
Degree : Branch :
Register No.
This is to certify that this is a bonafide record of the work done by the above student
with Register No. ______________________ of _________________________ Semester
M.E Degree in _________________________________________________ in
the_____________________________________________________________ Laboratory
during the academic year 2022 – 2023
Date:
RESULT
Thus the Data definition command, Data manipulation Command for inserting, deleting, updating and
relieving table and transaction Control Statement was executed successfully.
Ex. No: 2 a) DISTRIBUTED DATABASE DESIGN AND IMPLEMENTATION
Date: Implementation of Name Server
AIM
Develop a client server application which implements Name Server. Let the client like a web browser sends
a request containing a hostname, then a piece of software such as name server resolver sends a request to
the name server to obtain the IP address of a hostname.
Description
Name server is a client / server network communication protocol. Name server clients send request
to the server while name servers send response to the client. Client request contain a name which is
converted into in IP address known as a forward name server lookups while requests containing an IP
address which is converted into a name known as reverse name server lookups. Name server
implements a distributed database to store the name of all the hosts available on the internet. If a client
like a web browser sends a request containing a hostname, then a piece of software such as name
server resolver sends a request to the name server to obtain the IP address of a hostname. If name
server does not contain the IP address associated with a hostname then it forwards the request to
another name server. It IP address has arrived at the resolver, which in turn completes the request
over the internet protocol.
Program
import java.net.*;
import java.io.*;
import java.util.*;
public class DNS
{
public static void main(String[] args)
{
int n;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
do
{
System.out.println("\n Menu: \n 1. DNS 2. Reverse DNS 3. Exit \n");
System.out.println("\n Enter your choice");
n = Integer.parseInt(System.console().readLine());
if(n==1)
{
try
{
System.out.println("\n Enter Host Name ");
String hname=in.readLine();
InetAddress address;
address = InetAddress.getByName(hname);
System.out.println("Host Name: " + address.getHostName());
System.out.println("IP: " + address.getHostAddress());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
if(n==2)
{
try
{
System.out.println("\n Enter IP address");
String ipstr = in.readLine();
InetAddress ia = InetAddress.getByName(ipstr);
System.out.println("IP: "+ipstr);
System.out.println("Host Name: " +ia.getHostName());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}while(!(n==3));
}}
Output
RESULT
Thus the distributed database design and implementation was created successfully.
Ex. No: 2 b) TRIGGERS
Date:
AIM
To implement row level and statement level triggers
TRIGGERS
A trigger is a stored program invoked automatically in response to an event such as insert, update,
or delete that occurs in the associated table. For example, you can define a trigger that is invoked
automatically before a new row is inserted into a table.
MySQL supports triggers that are invoked in response to the INSERT, UPDATE or DELETE event.
The SQL standard defines two types of triggers: row-level triggers and statement-level triggers.
A row-level trigger is activated for each row that is inserted, updated, or deleted.
A statement-level trigger is executed once for each transaction regardless of how many rows are
inserted, updated, or deleted.
MySQL supports only row-level triggers. It doesn’t support statement-level triggers.
MANAGING MYSQL TRIGGERS
Create triggers – describe steps of how to create a trigger in MySQL.
Drop triggers – show you how to drop a trigger.
Create a BEFORE INSERT trigger – show you how to create a BEFORE INSERT trigger to maintain
a summary table from another table.
Create an AFTER INSERT trigger – describe how to create an AFTER INSERT trigger to insert data
into a table after inserting data into another table.
Create a BEFORE UPDATE trigger – learn how to create a BEFORE UPDATE trigger that validates
data before it is updated to the table.
Create an AFTER UPDATE trigger – show you how to create an AFTER UPDATE trigger to log the
changes of data in a table.
Create a BEFORE DELETE trigger – show how to create a BEFORE DELETE trigger.
Create an AFTER DELETE trigger – describe how to create an AFTER DELETE trigger.
Create multiple triggers for a table that have the same trigger event and time – MySQL 8.0 allows
you to define multiple triggers for a table that have the same trigger event and time.
Show triggers – list triggers in a database, table by specific patterns.
Query
mysql> CREATE TABLE employee(id int, name varchar(20), occupation varchar(20), working_hours
int);
mysql> Insert into employee values(1,”AAA”, “Actor”, 12), (2,”BBB”,”Teacher”,14);
mysql> select * from employee;
------+------+------------+------------------------+
| id | name | occupation | working_hours |
+------+------+------------+----------------------+
| 1 | AAA | Actor | 12 |
| 2 | BBB | Teacher | 14 |
+------+------+------------+----------------------+
BEFORE INSERT TRIGGER
mysql> DELIMITER $$
mysql> Create Trigger before_inserthour
-> BEFORE INSERT ON employee FOR EACH ROW
-> BEGIN
-> IF NEW.working_hours<0 THEN SET NEW.working_hours=0;
-> END IF;
-> END $$
mysql> insert into employee values(4,"DDD","Nurse",-12);
-> $$
mysql> select * from employee;
-> $$
mysql> show triggers;
-> $$
------+------+------------+------------------------+
| id | name | occupation | working_hours |
+------+------+------------+----------------------+
| 1 | AAA | Actor | 12 |
| 2 | BBB | Teacher | 14 |
| 4 | DDD | Nurse | 0 |
+------+------+------------+----------------------+
AFTER INSERT TRIGGER
mysql> create table emp_details1(id int,name varchar(25),occupation varchar(25),working_hours
int, Lastinserted Time);
mysql> DELIMITER $$
mysql> Create Trigger after_insert_details2
-> AFTER INSERT ON employee FOR EACH ROW
-> BEGIN
-> INSERT INTO emp_details1 VALUES (NEW.id, NEW.name, NEW.occupation,
NEW.working_hours, CURTIME( ));
-> END$$
mysql> INSERT into employee values(8,'MMM','Doctor',23);
-> $$
mysql> select * from employee;
-> $$
------+------+------------+------------------------+
| id | name | occupation | working_hours |
+------+------+------------+----------------------+
| 1 | AAA | Actor | 12 |
| 2 | BBB | Teacher | 14 |
| 4 | DDD | Nurse | 0 |
| 8 | MMM| Doctor | 23 |
+------+------+------------+----------------------+
mysql> select * from emp_details1;
-> $$
------+------+------------+--------------------------------------------+
| id | name | occupation | working_hours | Lastinserted |
+------+------+------------+------------------------------------------+
| 8 | MMM| Doctor | 23 | 21.18.59 |
+------+------+------------+------------------------------------------+
BEFORE UPDATE TRIGGER
mysql> DELIMITER $$
mysql> CREATE TRIGGER before_update2
-> BEFORE UPDATE ON employee FOR EACH ROW
-> BEGIN
-> DECLARE error_msg VARCHAR(200);
-> SET error_msg=('The working hours cannot be greater than 30');
-> IF new.working_hours>30 THEN
-> SIGNAL SQLSTATE '45000'
-> SET MESSAGE_TEXT=error_msg;
-> END IF;
-> END $$
mysql> update employee set working_hours=32 where id=3;
-> $$
-------------------------------+---------------------+-------------+
| error_msg |
+-----------------------------+---------------------+--------------+
| The working hours cannot be greater than 30 |
+-----------------------------+---------------------+--------------+
AFTER UPDATE TRIGGER
mysql> create table student(id int, name varchar(20), class int);
mysql> insert into student values(101,'AAA',5),(102,'BBB',8),(103,'CCC',4);
mysql> select * from student;
------+------+------------+---+
| id | name | class |
+------+------+------------+-+
| 101 | AAA | 5 |
| 102 | BBB | 8 |
| 103 | CCC | 4 |
+------+------+------------+--+
mysql> create table studentlog(user longtext,desc longtext);
mysql> select * from studentlog;
Empty Set
mysql> CREATE TRIGGER after_updatestu1
-> AFTER UPDATE ON student FOR EACH ROW
-> BEGIN
-> INSERT into studentlog VALUES (user( ), CONCAT('update', OLD.name,'Prev:' ,OLD.class, 'Pres:',
NEW.class));
-> END$$
mysql> UPDATE student SET class = class + 1;
-> $$
mysql> select * from student;
-> $$
------+------+------------+---+
| id | name | class |
+------+------+------------+-+
| 101 | AAA | 6 |
| 102 | BBB | 9 |
| 103 | CCC | 5 |
+------+------+------------+--+
mysql> select * from studentlog;
-> $$
------+------+------------+-----------------------------+
| user | pass |
+------+------+------------+---------------------------+
| root@localhost | updateAAAPrev:5 Pres:6 |
| root@localhost | updateAAAPrev:8 Pres:9 |
| root@localhost | updateAAAPrev:4 Pres:5 |
+------+------+------------+---------------------------+
BEFORE DELETE TRIGGER
mysql> select * from employee;
-> $$
------+------+------------+------------------------+
| id | name | occupation | working_hours |
+------+------+------------+----------------------+
| 1 | AAA | Actor | 12 |
| 2 | BBB | Teacher | 14 |
| 4 | DDD | Nurse | 0 |
| 8 | MMM| Doctor | 23 |
+------+------+------------+----------------------+
mysql> create table delemp1(id int PRIMARY KEY AUTO_INCREMENT, name varchar(30),
occupation varchar(20), deleted_time TIMESTAMP DEFAULT NOW( ));
mysql> CREATE TRIGGER before_delete1
-> BEFORE DELETE ON employee FOR EACH ROW
-> BEGIN
-> INSERT INTO delemp1(name,occupation) VALUES(OLD.name,OLD.occupation);
-> END$$
mysql> delete from employee where id=8;
-> $$
mysql> select * from employee;
-> $$
------+------+------------+------------------------+
| id | name | occupation | working_hours |
+------+------+------------+----------------------+
| 1 | AAA | Actor | 12 |
| 2 | BBB | Teacher | 14 |
| 4 | DDD | Nurse | 0 |
+------+------+------------+----------------------+
mysql> select * from delemp1;
-> $$
------+------+------------+----------------------------------------+
| id | name | occupation | deleted_time |
+------+------+------------+--------------------------------------+
| 8 | MMM | Doctor | 2022-05-11 21:49:51 |
+------+------+------------+---------------------------------------+
AFTER DELETE TRIGGER
mysql> create table empsalary(empid int, amount int);
-> $$
mysql> insert into empsalary values(101,5000),(102,4000),(103,3000),(104,8000);
-> $$
mysql> select * from empsalary;
-> $$
-------------+-----------+
| empid | amount |
+---------- +------------+
| 101 | 5000 |
| 102 | 4000 |
| 103 | 3000 |
| 104 | 8000 |
+----------+-------------+
mysql> create table totalsalary(total_budget int);
-> $$
mysql> insert into totalsalary(total_budget)
-> SELECT SUM(amount) from empsalary;
-> $$
mysql> select * from totalsalary;
-> $$
------+------+------------+
| total_budget |
+------+------+---------- +
| 20000 |
+------+------+-----------+
mysql> DELIMITER $$
mysql> CREATE TRIGGER after_delete
-> AFTER DELETE ON empsalary FOR EACH ROW
-> BEGIN
-> UPDATE totalsalary SET total_budget=total_budget-OLD.amount;
-> END $$
mysql> delete from empsalary where empid=103;
-> $$
mysql> select * from empsalary;
-> $$
-------------+-----------+
| empid | amount |
+---------- +------------+
| 101 | 5000 |
| 102 | 4000 |
| 104 | 8000 |
+----------+-------------+
mysql> select * from totalsalary;
-> $$
------+------+------------+
| total_budget |
+------+------+---------- +
| 17000 |
+------+------+-----------+
mysql> drop trigger after_delete;
-> $$
RESULT
Thus the trigger concept was executed successfully.
EX. NO: 2 C) ACCESSING A RELATIONAL DATABASE USING PHP, PYTHON AND R
Date:
AIM
RESULT
Thus the Relational Database accessed successfully using PHP, Python and R
Ex. No: 3 a) CREATING XML DOCUMENTS, DOCUMENT TYPE DEFINITION AND XML
SCHEMA
Date:
AIM
To create XML documents, Document Type Definition and XML Schema
XML Documents
An XML document is a basic unit of XML information composed of elements and other markup in an
orderly package. An XML document can contains wide variety of data. For example, database of numbers,
numbers representing molecular structure or a mathematical equation.
XML Document Example
A simple document is shown in the following example
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
The following image depicts the parts of XML document.
Document Prolog comes at the top of the document, before the root element. This section contains −
XML declaration
Document type declaration
Document Elements Section
Document Elements are the building blocks of XML. These divide the document into a hierarchy of sec-
tions, each serving a specific purpose. You can separate a document into multiple sections so that they can
be rendered differently, or used by a search engine. The elements can be containers, with a combination
of text and other elements.
DOCUMENT TYPE DEFINITION
A Document Type Definition (DTD) describes the tree structure of a document and something about
its data. It is a set of markup affirmations that actually define a type of document for the SGML family,
like GML, SGML, HTML, XML.
PROGRAM
<?xml version="1.0"?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>
<first>Rohit</first>
<last>Sharma</last>
</name>
<email>[email protected]</email>
<phone>9876543210</phone>
<birthday>
<year>1987</year>
<month>June</month>
<day>23</day>
</birthday>
</address>
OUTPUT
XML SCHEMA
XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and
validate the structure and the content of XML data. XML schema defines the elements, attributes and
data types. Schema element supports Namespaces. It is similar to a database schema that describes
the data in a database.
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = "contact">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
RESULT
Thus XML Documents, Document Type Definition and XML Schema Was Created successfully
Ex. No: 3 b) CREATING AND EXTRACTING XML DOCUMENTS FROM RELATIONAL DATABASE
Date:
AIM
To create and Extract XML documents from Relational Database
PROCEDUR
1) Create a simple Java project through java application. We have created the class file with the name
JavaStudents.
2) Create an XML file in any folder using notepad. We have created an XML file with name XML-
File.xml and write the following data into it.
3) Download dom-2.3.0-jaxb-1.0.6.jar file
4) Add jar file through Libraries.
5) Run the project
PROGRAM
XMLFile.xml
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="501">
<firstName>Sunil</firstName>
<lastName>Yadav</lastName>
<percentage>72%</percentage>
</student>
<student id="502">
<firstName>Trilok</firstName>
<lastName>Reddy</lastName>
<percentage>86%</percentage>
</student>
<student id="503">
<firstName>Mallikarjun</firstName>
<lastName>Tiger</lastName>
<percentage>98%</percentage>
</student>
<student id="504">
<firstName>Neelima</firstName>
<lastName>Lakshmi</lastName>
<percentage>MP</percentage>
</student>
<student id="505">
<firstName>Abhi</firstName>
<lastName>Shambu</lastName>
<percentage>55%</percentage>
</student>
</students>
JavaStudents.java
package javastudents;
import java.io.BufferedReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.io.InputStreamReader;
public class JavaStudents
{
public static void main(String[] args)
{
try
{
File file = new File("D:\\XMLFile.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
Element root = document.getDocumentElement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter User Id");
String id=br.readLine();
NodeList nList = document.getElementsByTagName("student");
System.out.println(root.getNodeName());
System.out.println("============================");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(temp);
System.out.println("");
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
if(eElement.getAttribute("id").equals(id))
{
System.out.println("Student id : " + eElement.getAttribute("id"));
System.out.println("First Name : " +
eElement.getElementsByTagName("firstName").item(0).getTextContent());
System.out.println("Last Name : " +
eElement.getElementsByTagName("lastName").item(0).getTextContent());
System.out.println("Percentage : " +
eElement.getElementsByTagName("percentage").item(0).getTextContent());
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
OUTPUT
RESULT
Thus the creating and Extracting XML documents from Relational Database was done successfully
Ex. No: 4 CREATING DATABASES USING MONGODB, DYNAMODB, VOLDEMORT KEY-VALUE
Date: DISTRIBUTED DATA STORE HBASE AND NEO4J
AIM
To Creating Databases using Mongodb, Dynamodb, Voldemort Key-Value Distributed Data Store Hbase
and Neo4j
QUERY
A MongoDB Database is the container for all the collections, where Collection is a bunch of MongoDB
documents similar to tables in RDBMS and Document is made up of the fields similar to a tuple in RDBMS,
but it has a dynamic schema here.
CREATING A NEW DATABASE
In the mongo shell, you can create a database with the help of the following command:
Syntax
use database_name
Example
Collection
Collections are just like tables in relational databases, they also store data, but in the form of documents.
A single database is allowed to store multiple collections.
Creating collection
After creating database now we create a collection to store documents. The collection is created using
the following syntax:
db.collection_name.insertOne({..})
Here, insertOne() function is used to store single data in the specified collection. And in the curly braces
{} we store our data or in other words, it is a document.
Document
In MongoDB, the data records are stored as BSON documents. Here, BSON stands for binary
representation of JSON documents, although BSON contains more data types as compared to JSON. The
document is created using field-value pairs or key-value pairs and the value of the field can be of any
BSON type.
Syntax
{
field1: value1
field2: value2
....
fieldN: valueN
}
Inserting a single document without _id field:
Inserting a document in the student collection without _id field using db.collection.insertOne() method.
RESULT
Thus the Creating Databases using Mongodb, Dynamodb, Voldemort Key-Value Distributed Data Store
Hbase and Neo4j was done successfully.
Ex. No: 5 IMPLEMENTING ACCESS CONTROL IN RELATIONAL DATABASES
Date:
AIM
To implementing Access Control in Relational Databases
CREATE TABLE
CREATE TABLE roles
(
role_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
role_name VARCHAR(50) NOT NULL,
PRIMARY KEY (role_id)
);
CREATE TABLE permissions
(
perm_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
perm_desc VARCHAR(50) NOT NULL,
PRIMARY KEY (perm_id)
);
CREATE TABLE role_perm
(
role_id INTEGER UNSIGNED NOT NULL,
perm_id INTEGER UNSIGNED NOT NULL,
FOREIGN KEY (role_id) REFERENCES roles(role_id),
FOREIGN KEY (perm_id) REFERENCES permissions(perm_id)
);
CREATE TABLE user_role
(
user_id INTEGER UNSIGNED NOT NULL,
role_id INTEGER UNSIGNED NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (role_id) REFERENCES roles(role_id)
);
Create Role.php
<?php
class Role
{
protected $permissions;
protected function __construct() {
$this->permissions = array();
}
// return a role object with associated permissions
public static function getRolePerms($role_id) {
$role = new Role();
$sql = "SELECT t2.perm_desc FROM role_perm as t1
JOIN permissions as t2 ON t1.perm_id = t2.perm_id
WHERE t1.role_id = :role_id";
$sth = $GLOBALS["DB"]->prepare($sql);
$sth->execute(array(":role_id" => $role_id));
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$role->permissions[$row["perm_desc"]] = true;
}
return $role;
}
// check if a permission is set
public function hasPerm($permission) {
return isset($this->permissions[$permission]);
}
}
create the file PrivilegedUser.php
<?php
class PrivilegedUser extends User
{
private $roles;
public function __construct() {
parent::__construct();
}
// override User method
public static function getByUsername($username) {
$sql = "SELECT * FROM users WHERE username = :username";
$sth = $GLOBALS["DB"]->prepare($sql);
$sth->execute(array(":username" => $username));
$result = $sth->fetchAll();
if (!empty($result)) {
$privUser = new PrivilegedUser();
$privUser->user_id = $result[0]["user_id"];
$privUser->username = $username;
$privUser->password = $result[0]["password"];
$privUser->email_addr = $result[0]["email_addr"];
$privUser->initRoles();
return $privUser;
} else {
return false;
}
}
// populate roles with their associated permissions
protected function initRoles() {
$this->roles = array();
$sql = "SELECT t1.role_id, t2.role_name FROM user_role as t1
JOIN roles as t2 ON t1.role_id = t2.role_id
WHERE t1.user_id = :user_id";
$sth = $GLOBALS["DB"]->prepare($sql);
$sth->execute(array(":user_id" => $this->user_id));
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->roles[$row["role_name"]] = Role::getRolePerms($row["role_id"]);
}
}
// check if user has a specific privilege
public function hasPrivilege($perm) {
foreach ($this->roles as $role) {
if ($role->hasPerm($perm)) {
return true;
}
}
return false;
}
}
OUTPUT
RESULT
Thus the Access Control in Relational Databases was created successfully