0% found this document useful (0 votes)
20 views

DBMS Final Lab Manual

Data base Managing system

Uploaded by

muthu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

DBMS Final Lab Manual

Data base Managing system

Uploaded by

muthu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Name :

Reg.No : Semester :

Degree : Branch :

Subject : Subject Code:


BONAFIDE CERTIFICATE

Name of the Student: _________________________________

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

Staff-In-Charge Head of the Dept.

Date:

Submitted for the Practical Examination held on __________________

Internal Examiner External Examiner


INDEX

EX DATE NAME OF THE EXPERIMENT PAGE MARKS STAFF SIGN


NO. NO.
EX DATE NAME OF THE EXPERIMENT PAGE MARKS STAFF SIGN
NO. NO.
Ex. No: 1 DDL, DML AND TCL FOR INSERTING, DELETING, UPDATING, RETRIEVING TABLES
Date:
AIM
To create table and execute data definition command, data manipulation command for inserting,
deleting, updating retrieving tables and transaction control Statement.
DATA DEFINITION COMMAND
DDL Command used to define database schema, it deals with description of dB schema.
 CREATE
 ALTER
 DROP
 TRUNCATE
 RENAME
DATA MANIPULATION COMMAND
DML command deals with manipulation of data Present in a database.
 INSERT
 DELETE
 UPDATE
DATA QUERY COMMAND
Data query Language used to fetch data from tables based on condition.
 SELECT
TRANSACTION CONTROL STATEMENT
It is used to manage transaction in the database TCL allows the student to the group together
in the logical transaction.
 Commit
 Rollback
 Savepoint
QUERIES
mysql> create database userdatabase;
Query OK, 1 row affected (1.50 sec)
mysql> use userdatabase;
Database changed
mysql> create table student (regno int, name varchar(25),age int, department varchar(20));
Query OK, 0 rows affected (1.15 sec)
mysql> insert into student (regno,name,age,department) values (101,'Raju',23,'CSE'),
(102,'Nega',24,'EEE'), (103,'Alex',21,'MECH');
Query OK, 3 rows affected (0.09 sec)
mysql> select * from student;
+-------+------+------+------------+
| regno | name | age | department |
+-------+------+------+------------+
| 101 | Raju | 23 | CSE |
| 102 | Nega | 24 | EEE |
| 103 | Alex | 21 | MECH |
+-------+------+------+------------+
mysql> rename table student to stu;
Query OK, 0 rows affected (0.64 sec)
mysql> select * from stu;
+-------+------+------+------------+
| regno | name | age | department |
+-------+------+------+------------+
| 101 | Raju | 23 | CSE |
| 102 | Nega | 24 | EEE |
| 103 | Alex | 21 | MECH |
+-------+------+------+------------+
mysql> alter table stu add cit varchar(20);
mysql> select * from stu;
+-------+------+------+------------+------+
| regno | name | age | department | cit |
+-------+------+------+------------+------+
| 101 | Raju | 23 | CSE | NULL |
| 102 | Nega | 24 | EEE | NULL |
| 103 | Alex | 21 | MECH | NULL |
+-------+------+------+------------+------+
mysql> update stu set cit='Madurai' where regno=101;
mysql> update stu set cit='Theni' where regno=102;
mysql> update stu set cit='Trichy' where regno=103;
mysql> select * from stu;
+-------+------+------+------------+---------+
| regno | name | age | department | cit |
+-------+------+------+------------+---------+
| 101 | Raju | 23 | CSE | Madurai |
| 102 | Nega | 24 | EEE | Theni |
| 103 | Alex | 21 | MECH | Trichy |
+-------+------+------+------------+---------+
mysql> delete from stu where name='Raju';
mysql> select * from stu;
+-------+------+------+------------+--------+
| regno | name | age | department | cit |
+-------+------+------+------------+--------+
| 102 | Nega | 24 | EEE | Theni |
| 103 | Alex | 21 | MECH | Trichy |
+-------+------+------+------------+--------+
mysql> commit;
mysql> start transaction;
mysql> insert into stu values(103,'Durga',21,'CSE','Coimbatore');
mysql> savepoint A;
mysql> insert into stu values(104,'Rani',23,'CSE','Tirunelveli');
mysql> savepoint B;
mysql> select * from stu;
+-------+-------+------+------------+-------------+
| regno | name | age | department | cit |
+-------+-------+------+------------+-------------+
| 102 | Nega | 24 | EEE | Theni |
| 103 | Alex | 21 | MECH | Trichy |
| 103 | Durga | 21 | CSE | Coimbatore |
| 104 | Rani | 23 | CSE | Tirunelveli |
+-------+-------+------+------------+-------------+
mysql> rollback to savepoint A;
mysql> select * from stu;
+-------+-------+------+------------+------------+
| regno | name | age | department | cit |
+-------+-------+------+------------+------------+
| 102 | Nega | 24 | EEE | Theni |
| 103 | Alex | 21 | MECH | Trichy |
| 103 | Durga | 21 | CSE | Coimbatore |
+-------+-------+------+------------+------------+
SIMPLE QUERIES
mysql> insert into student1 values(1,'Prasanna','CSE');
mysql> insert into student1 values(2,'Mithun','ECE');
mysql> insert into student1 values(3,'Naga','CSE');
mysql> insert into student1 values(4,'shyam','EEE');
mysql> select * from student1;
+-------+----------+------+
| stuid | name | dept |
+-------+----------+------+
| 1 | Prasanna | CSE |
| 2 | Mithun | ECE |
| 3 | Naga | CSE |
| 4 | shyam | EEE |
+-------+----------+------+
mysql> select DISTINCT dept from student1;
+------+
| dept |
+------+
| CSE |
| ECE |
| EEE |
+------+
mysql> select * from student1 where dept='CSE' ORDER BY stuid DESC;
+-------+----------+------+
| stuid | name | dept |
+-------+----------+------+
| 3 | Naga | CSE |
| 1 | Prasanna | CSE |
+-------+----------+------+
mysql> select dept, count(*) from student1 GROUP BY dept;
+------+----------+
| dept | count(*) |
+------+----------+
| CSE | 2|
| ECE | 1|
| EEE | 1|
+------+----------+
mysql> select dept, count(*) from student1 GROUP BY dept HAVING count(dept)>1;
+------+----------+
| dept | count(*) |
+------+----------+
| CSE | 2|
+------+----------+
mysql> select * from student1 where dept='CSE' OR stuid>3;
+-------+----------+------+
| stuid | name | dept |
+-------+----------+------+
| 1 | Prasanna | CSE |
| 3 | Naga | CSE |
| 4 | shyam | EEE |
+-------+----------+------+
mysql> select * from student1 where dept='CSE' AND stuid>3;
Empty set (0.00 sec)
mysql> select * from student1 where dept='CSE' AND stuid>2;
+-------+------+------+
| stuid | name | dept |
+-------+------+------+
| 3 | Naga | CSE |
+-------+------+------+
mysql> select * from student1 where dept IN ('EEE','ECE');
+-------+--------+------+
| stuid | name | dept |
+-------+--------+------+
| 2 | Mithun | ECE |
| 4 | shyam | EEE |
+-------+--------+------+
mysql> select * from student1 where dept NOT IN ('EEE','ECE');
+-------+----------+------+
| stuid | name | dept |
+-------+----------+------+
| 1 | Prasanna | CSE |
| 3 | Naga | CSE |
+-------+----------+------+
mysql> select * from student1 where stuid between 1 and 3;
+-------+----------+------+
| stuid | name | dept |
+-------+----------+------+
| 1 | Prasanna | CSE |
| 2 | Mithun | ECE |
| 3 | Naga | CSE |
+-------+----------+------+
PRIMARY KEY CONSTRAINT
mysql> create table employee (empid int primary key, name varchar(35), salary int);
mysql> insert into employee values(5001, 'AAA',10000);
mysql> insert into employee values(5002, 'BBB',8000);
mysql> insert into employee values(5002, 'ABC',4000);
ERROR 1062 (23000): Duplicate entry '5002' for key 'employee.PRIMARY'
mysql> insert into employee values(5003, 'CCC',9200);
mysql> select * from employee;
+-------+------+--------+
| empid | name | salary |
+-------+------+--------+
| 5001 | AAA | 10000 |
| 5002 | BBB | 8000 |
| 5003 | CCC | 9200 |
+-------+------+--------+
FOREIGN KEY CONSTRAINT
mysql> create table empdetail(id int primary key, depname varchar(20), empid int, foreign
key(empid) references employee(empid));
mysql> insert into empdetail values(101,'Marketing',5001);
mysql> insert into empdetail values(102,'Admin',5002);
mysql> insert into empdetail values(103,'clerk',5004);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
(`userdatabase`.`empdetail`, CONSTRAINT `empdetail_ibfk_1` FOREIGN KEY (`empid`) REFERENCES
`employee` (`empid`))
mysql> select * from empdetail;
+-----+-----------+-------+
| id | depname | empid |
+-----+-----------+-------+
| 101 | Marketing | 5001 |
| 102 | Admin | 5002 |
+-----+-----------+-------+
NOT NULL CONSTRAINT, UNIQUE CONSTRAINT, CHECK CONSTRAINT
mysql> create table student(regno int UNIQUE, Name varchar(24) NOT NULL, age int
check(age>=18));
mysql> insert into student values (101,'uma',20);
mysql> insert into student values (101,'naga',23);
ERROR 1062 (23000): Duplicate entry '101' for key 'student.regno'

mysql> insert into student values (102,NULL,43);


ERROR 1048 (23000): Column 'Name' cannot be null

mysql> insert into student values (102,'naga',16);


ERROR 3819 (HY000): Check constraint 'student_chk_1' is violated.
mysql> insert into student values (103,'devi',NULL);
mysql> select * from student;
+-------+------+------+
| regno | Name | age |
+-------+------+------+
| 101 | uma | 20 |
| 103 | devi | NULL |
+-------+------+------+
DEFAULT CONSTRAINT
mysql> create table college (id int NOT NULL, name varchar(20), clgname varchar(20) DEFAULT
'SCE');
mysql> insert into college (id,name) values (1,'Aarthi'),(2,'Harshini'),(3,'Divya');
mysql> select * from college;
+----+----------+---------+
| id | name | clgname |
+----+----------+---------+
| 1 | Aarthi | SCE |
| 2 | Harshini | SCE |
| 3 | Divya | SCE |
+----+----------+---------+
SELECTION OPERATION
mysql> select * from college where id=1;
+----+--------+---------+
| id | name | clgname |
+----+--------+---------+
| 1 | Aarthi | SCE |
+----+--------+---------+
PROJECTION OPERATION
mysql> select id, name from college;
+----+----------+
| id | name |
+----+----------+
| 1 | Aarthi |
| 2 | Harshini |
| 3 | Divya |
+----+----------+
UNION OPERATION
mysql> create table csedept (regno int, name varchar(24));
mysql> create table ecedept(regno int, name varchar(23));
mysql> insert into csedept (regno,name) values (401,'AAA'), (402,'BBB');
mysql> insert into ecedept (regno,name) values (601,'ABC'), (602,'BCD');
mysql> select * from csedept;
+-------+------+
| regno | name |
+-------+------+
| 401 | AAA |
| 402 | BBB |
+-------+------+
mysql> select * from ecedept;
+-------+------+
| regno | name |
+-------+------+
| 601 | ABC |
| 602 | BCD |
+-------+------+
mysql> select * from csedept union select * from ecedept;
+-------+------+
| regno | name |
+-------+------+
| 401 | AAA |
| 402 | BBB |
| 601 | ABC |
| 602 | BCD |
+-------+------+
JOIN OPERATION
i) EQUI JOIN
mysql> create table A(id int, name varchar(20),fees int);
mysql> insert into A (id,name,fees) values(1,'Jeni',10000),(2,'Mike',3000),(3,'Fedo',2300);
mysql> select * from A;
+------+------+-------+
| id | name | fees |
+------+------+-------+
| 1 | Jeni | 10000 |
| 2 | Mike | 3000 |
| 3 | Fedo | 2300 |
+------+------+-------+
mysql> create table B(id int, dept varchar(20),phno int);
mysql> insert into B (id,dept,phno) values(1,'ECE',224435),(3,'EEE',3464560),(4,'MECH',235657);
mysql> select * from B;
+------+------+---------+
| id | dept | phno |
+------+------+---------+
| 1 | ECE | 224435 |
| 3 | EEE | 3464560 |
| 4 | MECH | 235657 |
+------+------+---------+
mysql> select name, phno from A join B on A.id=B.id;
+------+---------+
| name | phno |
+------+---------+
| Jeni | 224435 |
| Fedo | 3464560 |
+------+---------+
ii) LEFT OUTER JOIN
mysql> select * from A left outer join B on A.id=B.id;
+------+------+-------+------+------+---------+
| id | name | fees | id | dept | phno |
+------+------+-------+------+------+---------+
| 1 | Jeni | 10000 | 1 | ECE | 224435 |
| 2 | Mike | 3000 | NULL | NULL | NULL |
| 3 | Fedo | 2300 | 3 | EEE | 3464560 |
+------+------+-------+------+------+---------+
iii) RIGHT OUTER JOIN
mysql> select * from A right outer join B on A.id=B.id;
+------+------+-------+------+------+---------+
| id | name | fees | id | dept | phno |
+------+------+-------+------+------+---------+
| 1 | Jeni | 10000 | 1 | ECE | 224435 |
| 3 | Fedo | 2300 | 3 | EEE | 3464560 |
| NULL | NULL | NULL | 4 | MECH | 235657 |
+------+------+-------+------+------+---------+
NESTED QUERY
mysql> select name,fees from A where id in(select id from B);
+------+-------+
| name | fees |
+------+-------+
| Jeni | 10000 |
| Fedo | 2300 |
+------+-------+
AGGREGATE FUNCTION
mysql> create table stumark(id int, name varchar(20), mark int);
mysql> insert into stumark(id,name,mark) values(1,'AAA',56),(2,'BBB',97),(3,'CCC',78),(4,'DDD',89);
mysql> select * from stumark;
+------+------+------+
| id | name | mark |
+------+------+------+
| 1 | AAA | 56 |
| 2 | BBB | 97 |
| 3 | CCC | 78 |
| 4 | DDD | 89 |
+------+------+------+
mysql> select Avg(mark) from stumark;
+-----------+
| Avg(mark) |
+-----------+
| 80.0000 |
+-----------+
mysql> select sum(mark) from stumark;
+-----------+
| sum(mark) |
+-----------+
| 320 |
+-----------+
mysql> select Max(mark) from stumark;
+-----------+
| Max(mark) |
+-----------+
| 97 |
+-----------+
mysql> select Min(mark) from stumark;
+-----------+
| Min(mark) |
+-----------+
| 56 |
+-----------+
mysql> select count(Name) from stumark;
+-------------+
| count(Name) |
+-------------+
| 4|
+-------------+
VIEWS
Views in SQL are considered as a virtual table. A view also contains rows and columns. To create
the view, we can select the fields from one or more tables present in the database. A view can either have
specific rows based on certain condition or all the rows of a table.
SEQUENCES
Sequences area feature that some DBMS products implement to provide users with a mechanism
to generate unique values. The Sequence ensures that each call to it returns a unique value. This is
particularly important when the Sequence's result is used as a Primary Key.
SYNONYMS
In databases, a synonym is an alias or alternate name for a table, view, sequence, or other schema
object. They are used mainly to make it easy for users to access database objects owned by other users.
QUERY
mysql> use userdatabase;
Database changed
mysql> create table flowers(id int NOT NULL AUTO_INCREMENT,name varchar(20), quantity
int,primary key(ID));
mysql> insert into flowers (name,quantity) values ('jasmine',20),('rose',12),('lilly',30),('lotus',25);
mysql> select * from flowers;
+----+---------+----------+
| id | name | quantity |
+----+---------+----------+
| 1 | jasmine | 20 |
| 2 | rose | 12 |
| 3 | lilly | 30 |
| 4 | lotus | 25 |
+----+---------+----------+
mysql> delete from flowers where id=3;
mysql> select * from flowers;
+----+---------+----------+
| id | name | quantity |
+----+---------+----------+
| 1 | jasmine | 20 |
| 2 | rose | 12 |
| 4 | lotus | 25 |
+----+---------+----------+
3 rows in set (0.01 sec)
mysql> delete from flowers where id=3;
mysql> select * from flowers;
+----+---------+----------+
| id | name | quantity |
+----+---------+----------+
| 1 | jasmine | 20 |
| 2 | rose | 12 |
| 4 | lotus | 25 |
+----+---------+----------+
mysql> insert into flowers values(5,'mullai',45);
mysql> insert into flowers values(6,'Sembaruthi',45);
mysql> insert into flowers values(7,'sunflower',45);
mysql> select * from flowers;
id Name qunatity
1 jasmine 20
2 rose 12
4 lotus 25
5 mullai 45
6 sembaruthi 45
7 sunflower 45

mysql> create view infa As select id,name from flowers;


mysql> select * from infa;
id Name
1 jasmine
2 rose
4 lotus
5 mullai
6 sembaruthi
7 sunflower

mysql> alter view infa As select id,name,quantity from flowers;


mysql> select * from infa;
id Name qunatity
1 jasmine 20
2 rose 12
4 lotus 25
5 mullai 45
6 sembaruthi 45
7 sunflower 45

mysql> update infa set name='jathimullai' where id=5;


mysql> select * from infa;
id Name qunatity
1 jasmine 20
2 rose 12
4 lotus 25
5 jathimullai 45
6 sembaruthi 45
7 sunflower 45

mysql> delete from infa where id=6;


mysql> select * from infa;
id Name qunatity
1 jasmine 20
2 rose 12
4 lotus 25
5 mullai 45
7 sunflower 45

mysql> drop view infa;


mysql> select * from infa;
Error: userdata.infa does not exist

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

To access a Relational Database Using PHP, Python and R


ACCESS DATABASE THROUGH PHP
PROCEDURE
 Start XAMPP Server.
 Open localhost/phpmyadmin in your web browser.
 Create database of name staff and table of Name College.
 Write HTML and PHP code in your php application in a netbeans.
 Submit data through HTML Form.
 Verify the results
PROGRAM
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>GFG- Store Data</title>
</head>
<body>
<center>
<h1>Storing Form data in Database</h1>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</p>
<p>
<label for="Gender">Gender:</label>
<input type="text" name="gender" id="Gender">
</p>
<p>
<label for="Address">Address:</label>
<input type="text" name="address" id="Address">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
insert.php
<!DOCTYPE html>
<html>
<head>
<title>Insert Page page</title>
</head>
<body>
<center>
<?php
// servername => localhost
// username => root
// password => empty
// database name => staff
$conn = mysqli_connect("localhost", "root", "", "staff");
// Check connection
if($conn === false)
{
die("ERROR: Could not connect . " . mysqli_connect_error());
}
// Taking all 5 values from the form data(input)
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$gender = $_REQUEST['gender'];
$address = $_REQUEST['address'];
$email = $_REQUEST['email'];
// Performing insert query execution
// here our table name is college
$sql = "INSERT INTO college VALUES ('$first_name',
'$last_name','$gender','$address','$email')";
if(mysqli_query($conn, $sql))
{
echo "<h3>data stored in a database successfully."
. " Please browse your localhost php my admin"
. " to view the updated data</h3>";

echo nl2br("\n$first_name\n $last_name\n "


. "$gender\n $address\n $email");
}
else
{
echo "ERROR: Hush! Sorry $sql . " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
</center>
</body>
</html>
OUTPUT
ACCESS DATABASE THROUGH PYTHON
Create Database
import mysql.connector
db_connection = mysql.connector.connect(
host= "localhost",
user= "root",
passwd= "root"
)
# creating database_cursor to perform SQL operation
db_cursor = db_connection.cursor()
# executing cursor with execute method and pass SQL query
db_cursor.execute("CREATE DATABASE my_first_db")
# get list of all databases
db_cursor.execute("SHOW DATABASES")
#print all databases
for db in db_cursor:
print(db)
OUTPUT

Create a Table in MySQL with Python


import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="my_first_db"
)
db_cursor = db_connection.cursor()
#Here creating database table as student'
db_cursor.execute("CREATE TABLE student (id INT PRIMARY KEY, name VARCHAR(255))")
#Get database table'
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
print(table)
OUTPUT
Insert Operation with MySQL in Python
import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="my_first_db"
)
db_cursor = db_connection.cursor()
student_sql_query = "INSERT INTO student(id,name) VALUES(01, 'John')"
employee_sql_query = " INSERT INTO employee (id, name, salary) VALUES (01, 'John', 10000)"
#Execute cursor and pass query as well as student data
db_cursor.execute(student_sql_query)
#Execute cursor and pass query of employee and data of employee
db_cursor.execute(employee_sql_query)
db_connection.commit()
print(db_cursor.rowcount, "Record Inserted")
OUTPUT
2 Record Inserted

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.

Inserting a single document with _id field


In this example, we are inserting a document in the student collection with _id field using
db.collection.insertOne() method.
Updating Document
Updating a document in the employee collection. Here multiple documents matches the given filter, so
this method will update the first document among these documents like as shown in the below image :

Updating multiple fields in the document


In this example, we are updating multiple fields in the single document (“_id”:
ObjectId("5e49813692e6dfa3fc48dd74") ).
Deleting first document
Deleting first document from the contributor collection by passing empty document in the
db.collection.deleteOne() 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

You might also like