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

Cp4152-Database Practices Lab

This is very useful to students for go their knowledge of computer ..I will promise about this Document.students have to read this notes...these are only for students..to everyone will understand 8n this lecture notes...every students hast to grow up in this computer Information Technology field..

Uploaded by

silentkiller8778
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)
42 views

Cp4152-Database Practices Lab

This is very useful to students for go their knowledge of computer ..I will promise about this Document.students have to read this notes...these are only for students..to everyone will understand 8n this lecture notes...every students hast to grow up in this computer Information Technology field..

Uploaded by

silentkiller8778
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/ 55

1

S.NO DATE LISTS OF CONTENT MARKS SIGN

DATA DEFINITION LANGUAGE (DDL)


1 COMMANDS

CONSTRAINT
2

DATA MANIPULATION LANGUAGE


3

NESTED QUERIES/SUB QUERIES AND


4 JOINS

DATA BASE CONNECTIVITY


5

CREATING DATABASE USING MongoDB


6

CREATING XML DOCUMENT AND DTD


7

USING A RELATIONAL DATABASE TO


8 STORE THE XML DOCUMENT AS TEXT

VIEWS
9

TRIGGE
10
2

EXPERIMENT NO: 1 DATA DEFINITION LANGUAGE (DDL) COMMANDS

AIM:

To execute and verify the Data Definition Language commands.

THEORY

The commands used are:

CREATE - It is used to create a table.

ALTER – The structure of a table can be modified by using the ALTER TABLE command. This command is used to add
a new column, modify the existing column definition and to include or drop integrity constraint.

DROP - It will delete the table structure provided the table should be empty.

TRUNCATE - If there is no further use of records stored in a table and the structure has to be retained, and then the
records alone can be deleted.

DESC - This is used to view the structure of the table

PROCEDURE

CREATION OF TABLE:

SYNTAX:

create table<table name>(column1 datatype,column2 datatype...);

EXAMPLE:SQL>CREATE TABLE Employee ( EmpNo number(5), EName VarChar(15), Job Char(10) , DeptNo
number(3));

ALTER TABLE

(a) To Add column to existing Table

Syntax:
3

alter table table-name add(column-name datatype );

EXAMPLE: ALTER TABLE Employee ADD (phone_no char (20));

(b)To Add Multiple columns to existing Table

Syntax:

alter table table-name add(column-name1 datatype1, column-name2


datatype2, column-name3 datatype3);

EXAMPLE:

alter table Employee add(salary number(7), age(5));

Dropping a Column from a Table

Syntax:

ALTER TABLE <Table Name>DROP COLUMN <CoumnName>;

EXAMPLE:

ALTER TABLE Employee DROP COLUMN phone_no ;

Modifying Existing Columns

Syntax:
4

ALTER TABLE <Table Name>MODIFY (<CoumnName><Newdata type>(<size>));

EXAMPLE:

ALTER TABLE Employee MODIFY (EName VarChar(25));


5

RENAMING TABLES

Syntax:

Rename <oldtable> to <new table>;

EXAMPLE:

rename Employee to Employee 1;

TRUNCATE TABLE

.Syntax:

TRUNCATE TABLE <TABLE NAME>;

DESTROYING TABLES

Syntax:

DROP TABLE <TABLE NAME>;

Example:

DROP TABLE Employee;

Problems

Create the tables described below Table Name : PRODUCT_MASTER

Description : used to store product information

Column name Data type size

PRODUCTNO Varchar2 6

DESCRIPTION Varchar2 15

PROFITPERCENT Varchar2 4,2

UNITMEASURE Varchar2 10

QTYONHAND Number 8

Table Name : CLIENT_MASTER


6

Description : used to store client information

Column name Data type size

CLIENTNO Varchar2 6

NAME Varchar2 20

ADDRESS1 Varchar2 30

ADDRESS2 Varchar2 30

CITY Varchar2 15

PINCODE Number 8

STATE Varchar2 15

BALDUE Number 10,2

Table Name : SALESMAN_MASTER

Description : used to store salesman information working for the company

Column name Data type size

SALESMANNO Varchar2 6

SALESMANNAME Varchar2 20

ADDRESS1 Varchar2 30

ADDRESS2 Varchar2 30

CITY Varchar2 15

PINCODE Number 8

STATE Varchar2 15
7

Table Name : STUDENT

Description : used to store student information

Column name Data type size

SNO Number 5

SNAME Varchar2 20

AGE Number 5

SDOB Date

SMARK1 Number 4,2

SMARK2 Number 4,2

SMARK3 Number 4,4

Exercise on altering the table structure

Add a column called ‘telephone’ of data type ‘number’ and size =’10’ to the Client _Master table.

Change the size of Sellprice column in Product_Master to 10,2

Exercise on deleting the table structure along with the data

(a)Destroy the table Client_Master along with its data

Exercise on renaming the table

(a)Change the name of the Salesman_Master table to sman_mast

RESULT: The DDL commands have been executed successfully.


8

EXPERIMENT NO:2 CONSTRAINTS


AIM:

To implement Data Constraints.

THEORY

Constraints are the business Rules which are enforced on the data being stored
in a table are called Constraints

TYPES OF CONSTRAINTS:
1) Primary key
2) Foreign key/references
3) Check
4) Unique
5) Not null
6) Null
7) Default

PROCEDURE

(a) The PRIMARY KEY

The PRIMARY KEY defined at column level

Syntax:

CREATE TABLE tablename (Columnname1 DATATYPE CONSTRAINT


<constraintname1> PRIMARY KEY,Columnname2 DATATYPE,
columnname3 DATATYPE,.....);

EXAMPLE

SQL>create table Employee(empno number(4) primary key,ename


varchar2(10),job varchar2(6),sal number(5),deptno number(7));
9

The PRIMARY KEY defined at table level

Syntax:

CREATE TABLE tablename (Columnname1 DATATYPE, columnname2


DATATYPE, columnname3 DATATYPE, PRIMARY KEY (columnname1,
columnname2));

EXAMPLE

(b) CHECK CONSTRAINT

The CHECK Constraint defined at column level

Syntax:

CREATE TABLE tablename


(Columnname1 DATATYPE CHECK (logical expression), columnname2
DATATYPE, columnname3 DATATYPE,...);

EXAMPLE

CREATE TABLE Employee(empno number(3),ename varchar2(20),design


varchar2(15),sal number(5) CHECK(sal>500 and sal<10001),deptno
number(2));

The CHECK Constraint defined at table level

Syntax:

CREATE TABLE tablename


(Columnname1 DATATYPE, columnname2 DATATYPE, columnname3
DATATYPE, CHECK (logical expression1), CHECK (logical expression2));

EXAMPLE

CREATE TABLE Employee(empno number(3),ename varchar2(20), design


varchar2(15),sal number(5),deptno number(2), CHECK(sal>500 and
sal<1000));

(c) UNIQUE CONSTRAINT


10

The UNIQUE Constraint defined at the column level

Syntax

CREATE TABLE tablename (Columnname1 DATATYPE UNIQUE,


columnname2 DATATYPE UNIQUE, columnname3 DATATYPE ...);

EXAMPLE

sql>CREATE TABLE Employee(empno number(3),ename varchar2(20),


design varchar2(15),sal number(5), UNIQUE(design));

The UNIQUE Constraint defined at the the table level

Syntax

CREATE TABLE tablename (Columnname1 DATATYPE, columnname2


DATATYPE, columnname3 DATATYPE, UNIQUE (columnname1));

EXAMPLE

sql>create table Employee(empno number(3),ename varchar2(20),


design varchar2(15),sal number(5), UNIQUE(design));

(d) Not Null


Syntax

CREATE TABLE tablename(Columnname1 DATATYPE NOT NULL,


columnname2 DATATYPE NOT NULL,columnname3 DATATYPE,...);

EXAMPLE

sql>CREATE TABLE Employee(empno number(4),ename varchar2(20) NOT


NULL,design varchar2(20),sal number(3));

Problems
11

1. Create the tables described below

Table Name : PRODUCT_MASTER

Description : used to store product information

Column name Data type size Attributes

PRODUCTNO Varchar2 6 Primary


key/first letter
must start with
‘p’

DESCRIPTION Varchar2 15 Not Null

PROFITPERCENT Varchar2 4,2 Not Null

UNITMEASURE Varchar2 10 Not Null

QTYONHAND Number 8 Not Null

REORDERLVL Number 8 Not Null

SELLPRICE Number 8,2 Not


Null,cannot be
0

COSTPRICE Number 8,2 Not


Null,cannot be
0

Table Name : CLIENT_MASTER

Description : used to store client information

Column name Data type size Attributes

CLIENTNO Varchar2 6 Primary


key/first letter
must start with
‘C’
12

NAME Varchar2 20 Not Null

ADDRESS1 Varchar2 30

ADDRESS2 Varchar2 30

CITY Varchar2 15

PINCODE Number 8

STATE Varchar2 15

BALDUE Number 10,2

Table Name : SALESMAN_MASTER

Description : used to store salesman information working for the company

Column name Data type size Attributes

SALESMANNO Varchar2 6 Primary


key/first letter
must start with
‘S’

SALESMANNAME Varchar2 20 Not Null

ADDRESS1 Varchar2 30 Not Null

ADDRESS2 Varchar2 30

CITY Varchar2 15

PINCODE Number 8

STATE Varchar2 15

RESULT: The Data constraint have been executed successfully.


13
14

EXPERIMENT NO 3: DATA MANIPULATION LANGUAGE

AIM:

To execute the Data Manipulation Language (DML) commands in RDBMS.

OBJECTIVES

To understand Data Manipulation Language (DML) commands

THEORY

DML commands are the most frequently used SQL commands and is used to
query and manipulate the existing database objects. Some of the commands are
1. INSERT
This is used to add one or more rows to a table. The values are separated
by commas and the data types char and date are enclosed in apostrophes.
The values must be entered in the same order as they are defined.
2. SELECT
It is used to retrieve information from the table.it is generally referred to
as querying the table. We can either display all columns in a table or only
specify column from the table.
3. UPDATE
It is used to alter the column values in a table. A single column may be
updated or more than one column could be updated.
4. DELETE
After inserting row in a table we can also delete them if required. The
delete command consists of a from clause followed by an optional where
clause

PROCEDURE

INSERT COMMAND

(a) Inserting a single row into a table:


Syntax:

insert into <table name> values (<expression1>,<expression2>)

Example:
15

SQL>INSERT INTO EMPLOYEE VALUES(101,'MANU','LECTURER',15000);

(b) Inserting more than one record using a single insert commands:

Syntax:

insert into <table name> values (&col1, &col2, ….)

Example:

SQL> INSERT INTO EMPLOYEE


VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY');

( c) Skipping the fields while inserting:

Insert into <tablename>(<column name1>,<column name3>)>values


(<expression1>,<expression3>);
Other way is to give null while passing the values.

SELECT COMMAND

(a) view all rows and all columns

Syntax:
Select * from
tablename;

Example:

Select * from Employee;

(b) Selected Columns And All Rows

Syntax:
Select <column1>,<column2> from tablename;

Example:
16

Select empno, empname from Employee;

(c)Selected Columns And selected Rows

Syntax:

SELECt <column1>, <column2> FROM <tablename> WHERE <condition> ;

Example:

Select empno, empname from Employee where designation=’lecturer’;

(c)Eliminating duplicate rows

Syntax:
SELECT DISTINCT <column1>, <column2> FROM <tablename>

Example:

Select distinct empname from Employee;

UPDATE COMMAND

(b)updating all rows

Syntax:

update tablename set


columnname1>=<exprssion1>,<columnname2>=<exprssion2>;
Example:

Update Employee set Designation = ‘lecturer’;

(b)updating records conditionally


Syntax:
17

update tablename set field=values where condition;


Example:

Update Employeeemp set sal = 10000 where empno=135;

DELETE COMMAND

(b)Removal of all rows


Syntax:

Delete from <table name> ;


Example:

Delete from emp;


(b)removal of specific rows :

Delete from <table name> where <condition>;


Example:

delete from emp where empno=135;


18

Problems
Product Descripti Profitpe unitmeas qtyonha sellpri Cost
No on rcent ure nd ce price
P00001 Tshirt 5 piece 200 350 250
P00065 Shirt 6 piece 150 500 350
P00032 Jeans 5 piece 100 600 450
P00324 Skirts 4 piece 120 750 500
P02345 CottonJe 3 piece 80 850 550
ans

1. Insert the following data into their respective tables.


Data for CLIENT_MASTER table
ClientNo Name City Pincode State BalDue
C00001 Ivan Mumbai 400054 Maharashtra 15000
C00002 Ashwini Chennai 780001 TamilNadu 0
C00003 Joshi Mangalore 560001 Karnataka 5000
C00004 Deepak Chennai 780001 TamilNadu 0
C00005 Sharma Mumbai 400054 Maharashtra 2000
19

2. Data for PRODUCT_MASTER table

Sales Name Address1 Address2 city Pincode State


manN
o
S0000 Aman A/4 Worli Mumbai 400002 Maharashtra
1
S0000 Omkar 65 Nariman Mumbai 400001 Maharashtra
2
S0000 Raj P-7 Bandra Mumbai 400032 Maharashtra
3
S0000 Ashish A/5 Juhu Mumbai 400044 Maharashtra
4
3. Data for SALESMAN_MASTER table

4. Exercise on retrieving records from a table


a. Find out the names of all clients
b. Retrieve the entire contents of the Client _master table
c. Retrieve the list of names,city and the state of all the clients
d. List the various products available from the Product _Master table
e. List all the clients who are located in Mumbai
f. Find the names of salesmen who have a salary equal to Rs.3000
5. Exercise on updating the records on a table

a. Change the city of ClientNo’C00005’ to ‘Bangaluru’.


20

b. Change the cBalDue of ClientNo’C00001’ to Rs.1000.


c. Change the costprice of ‘Shirt ‘ to Rs.450.
d. Change the city of salesman to Pune.
6. Exercise on deleting the records in a table
a. Delete all salesman from the Salesman_master whose salaries are
equal to Rs.3500.
b. Delete all sproducts from the Product_master where quantity on
hand is equal to 100
c. Delete from the Client_master where the column state holds the
value ‘Tamilnadu’.

RESULT: The DML have been executed successfully.


21

EXPERIMENT NO:4 NESTED QUERIES/SUB QUERIES AND JOINS

AIM:

To implement e nested queries and joins on the given table

OBJECTIVES

To understand nested queries and joins.

THEORY

a) NESTED QUERIES:

A sub query is a query within a query. In Oracle, we can create sub queries
within your SQL statements. These sub queries can reside in the WHERE
clause, the FROM clause, or the SELECT clause.

b) JOINS:

Join is a query in which data is returned from two or more tables.

Natural join:
It returns the matching rows from the table that are being joined
.
Syntax:
>select <attribute> from TN where TN1.attribute=TN2.attribute.
Inner join:
It returns the matching rows from the table that are being joined.

Syntax:
>select <attribute> from TN1 innerjoin TN2 on TN1.attribute=TN2.attribute.
Left outer join:
It returns all the rows from the table1 even when they are unmatched.

Syntax:
5. select <attribute> from TN1 left outer join TN2 on
TN1.attribute=TN2.attribute.
2. select <attribute> from TN where TN1.attribute(+)=TN2.attribute.
22

Right outer join:


It returns all the rows from the table2 even when they are unmatched.

Syntax:
4. select <attribute> from TN1 right outer join TN2 on
TN1.attribute=TN2.attribute.
2. select <attribute> from TN where TN1.attribute=(+)TN2.attribute.
Full join:

It is the combination of both left outer and right outer join.


Syntax:
>select <attribute> from TN1 full join TN2 on TN1.attribute=TN2.attribute.

PROCEDURE

NESTED QUERIES -

SQL> desc emp_det;


Name Null? Type
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(25)
ADDRESS VARCHAR2(30)
BASIC_SAL NUMBER(12,2)
JOB_STATUS VARCHAR2(15)
DNO NUMBER(3)

SQL> desc pro_det;


Name Null? Type

PNO NOT NULL NUMBER(3)


PNAME VARCHAR2(30)
NO_OF_STAFF NUMBER(3)

SQL> desc work_in;

Name Null? Type

PNO NUMBER(3)
ENO NUMBER(3)
23

PJOB CHAR(12)

SQL> select * from emp_det;

EN ENAME ADDRESS BASIC_SA JOB_STATU DNO


O L S
1 SaravanaKuma GandhiNagar 8000 Manager 10
r
2 Mahendran RainbowColon 5000 Supervisor 10
y
3 RajKumar EastCoastRoad 10000 Professor 2
4 Shirley KKnagar 8000 AsstManager 3

SQL> select * from Pro_det;

PNO PNAME NO_OF_STAFF

1 DBMS 2
2 COMPILER 3
3 C1 1

SQL> select * from work_in;

PNO ENO PJOB

1 1 Programmer
2 1 Analyst
1 2 Analyst
2 2 Programmer

NESTED QUERIES

(i) SQL> select ename from emp_det where dno not in(select dno from
emp_det where ename ='SaravanaKumar');

ENAME
24

RajKumar
Shirley

(ii)SQL> select ename, dno from emp_det where dno = (select dno from
emp_det where ename ='RajKumar');

ENAME DNO
RajKumar 2

(iii)SQL> select ename from emp_det where eno in(select eno from work_in
where pno = (select pno from pro_det where pname = 'DBMS')) order by
ename;
ENAME
Mahendran
SaravanaKumar
(iv)SQL> select ename, basic_sal from emp_det where dno = 2 and
basic_sal>(select max(basic_sal) from emp_det where dno = 10) order by
ename;

ENAME BASIC_SAL
RajKumar 10000

(v)SQL> select pno,pname from pro_det where exists(select pno from work_in
where work_in.pno =pro_det.pno);

PNO PNAME
1 DBMS
2 COMPILER

(vi)SQL>select ename, job_status,basic_sal from emp_det where


(dno,basic_sal) in (select dno,basic_sal from emp_det where ename
='RajKumar');

ENAME JOB_STATUS BASIC_SAL


RajKumar Professor 10000
25

(vii)SQL>select * from emp_det where basic_sal=(select max(basic_sal) from


emp_det);
ENO ENAME ADDRESS BASIC_SAL JOB_STATUS DNO
3 RajKumar EastCoastRoad 10000 Professor 2

(viii)SQL>select max(basic_sal) from emp_det where basic_sal< (select


max(basic_sal) from emp_det);

MAX(BASIC_SAL)
8000

(ix)SQL> select * from emp_det where basic_sal < (select avg(basic_sal) from
emp_det);

ENO ENAME ADDRESS BASIC_SAL JOB_STATUS DNO

2 Mahendran RainbowColony 5000 Supervisor 10

JOINS
SQL> create table emp(name varchar2(20),salary number(10));
Table created.
SQL> select * from emp;
NAME SALARY
ashu 10000
asma 1200
asif 2000
arif 1000
niyas 3000
SQL> create table emp1(name varchar2(20),empid number(10));
Table created.
.
SQL> select * from emp1;
NAME EMPID
fathi 12
sumi 32
priya 11
wahab 10
sweety 9
asma 1200
26

6 rows selected.
NATURAL JOIN
************
SQL>select emp.name,salary from emp,emp1 where emp.name=emp1.name
NAME SALARY
asma 1200
LEFT OUTER JOIN
SQL>select emp.name,salary from emp left outer join emp1 on
emp.name=emp1.name
NAME SALARY
asma 1200
asif 2000
arif 1000
niyas 3000
ashu 10000
RIGHT OUTER JOIN

SQL>select emp1.name,empid from emp right outer join emp1 on


emp.name=emp1.name
NAME EMPID
asma 1200
sweety 9
sumi 32
wahab 10
fathi 12
priya 11
6 rows selected.
FULL JOIN
SQL>select emp1.name,emp.name,emp1.empid,salary from emp full join emp1
on
emp.name=emp1.name
NAME NAME EMPID SALARY
asma asma 1200 1200
asif 2000
arif 1000
niyas 3000
ashu 10000
sweety 9
sumi 32
27

wahab 10
fathi 12
priya 11
10 rows selected.

RESULT:
Thus the nested queries and join operations are executed and verifiedin DBMS.
28

EXPERIMENT NO: 5

DATABASE CONNECTIVITY

AIM

Create a php program that allows to enter the employee details into a database.

To create an application program that process a query which returns the grade
result of a student after processing the marks table.

OBJECTIVES

To understand PHP mysql database connectivity.

To study the concept of connecting database using an application program


(PHP) and process results after manipulating the database table

Requirements:

Mysql database software, LAMP Server and html.

PROCEDURE

Create a database in Mysql. Create a 'marks' table with fields regno, name,
batch, mark1, mark2 and mark3. Write a function which finds the total marks
and if the total marks is greater than 225 then the result is categorized as
“Distinction”, if the total marks is less than 225 , the result is “firstclass”, it the
total marks is less than 180, the result is “second class”, if the total marks is less
than 150 the result is “passed”. If the marks in any one of the subject is less than
40 the result is “Failed”.

1. create a form in PHP/JAVA

2. create a database in mysql

3. provide the database connectivity

4. retrieve the details of employee through forms

php code:
29

<?php

$user_name = "root";

$password = "";

$server = "localhost";

$database = "mysql";

$regno = $_POST['regno'];

//$regno = 1;

$db_handle = mysql_connect($server, $user_name, $password);

if (!$db_handle)

{
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db_found = mysql_select_db($database);
if ($db_found)
{
//echo "Database found";
$SQL = "SELECT * FROM marks WHERE regno = '".$regno."'";
$result_set = mysql_query($SQL);
$record = mysql_fetch_array($result_set);
echo "<BR>MARKLIST";
echo "<BR>Reg No..:".$record['regno'];
echo "<BR>Name.....".$record['name'];
echo "<BR>Group....".$record['batch'];
echo "<BR>Mark1....".$record['mark1'];
echo "<BR>Mark2....".$record['mark2'];
30

echo "<BR>Mark3...:".$record['mark3'];
echo "<BR>Result..:".
compute_result($record['mark1'],$record['mark2'],$record['mark3']);

}
else
{

echo "<BR>Database not Found";


}
mysql_close($db_handle);
function compute_result($m1, $m2, $m3)
{
$tmarks = $m1 + $m2 + $m3;
if (($m1<40) || ($m2<40) || ($m3<40))
$result = "Failed";
elseif ($tmarks < 150)
$result = "Passed";
elseif ($tmarks<180)
$result = "Second Class";
elseif ($tmarks<225)
$result = "First Class";
else
$result = "Distinction";
return $result;
}
?>
31

Html code:

<html>
<body>
<FORM Method = "post" Action="connect1.php">
Reg No:
<INPUT Type = "text" name = "regno"> <BR>
<INPUT type = "submit" value = "Show Result">
</FORM>
</body>
</html> OUTPUT

RESULT
32

Experiment NO:6 CREATING DATABASE USING MongoDB


AIM
TO Create a Database Using MongoDB

Procedure
Installing MongoDB

If you haven’t installed MongoDB yet, let’s do it first. Download the MongoDB package suitable
for your OS. Download the msi/zip file compatible with your OS and install the application. (I am
not going to describe the installation process in detail, as it is straightforward.)

I assume now you have installed the MongoDB database successfully. Open your CMD and
type mongod –version to verify your installation. If you get an output similar to the result in the
picture below, everything is perfect.

Accessing the Mongo shell

When you install MongoDB, a CLI tool called Mongo shell will be installed along with it. You can use it to give
commands to the MySQL server. In order to get access to the mongo shell, you have to start the server with the
following command:

Copy

net start MongoDB

If you get this output, the MongoDB server has successfully started:
33

Next, we should run the MongoDB shell. To do that, type the command mongo in the CMD.

Now you are in the MongoDB shell, where you can execute commands to:

Create databases

Insert data

Edit and delete data from databases

Issue administrative commands

Creating a Mongo database

As I said earlier, there is no ‘create database’ command in MongoDB. It doesn’t mean there is no way to create a
database—of course there is. Let’s see how, by creating a database called Company using the shell.

MongoDB has a keyword called ‘use,’ which is used to switch to a specified database. For example, if you want
to connect with an existing database named Employee, you can use the command ‘use Employee’ to connect
with it. However, if there is no database as Employee, the command ‘use’ will create it and connects you to it.
Let’s use the ‘use’ command to create our database.

Copy
34

use Company

When you use the command, you will see the following output:

Mongo has created the company database and connected you to it. You can use the db command to confirm,
which will display the currently connected database.

You might want to see all the existing databases before creating a new database. You can do it with the show
dbs command, and it will return the following result:

Installing MongoDB creates three default databases:

Admin

Config

Local

Surprisingly, the database we just created is not listed. This is because MongoDB doesn’t truly create the
database until we save values to it.

One of the critical features in NoSQL databases like MongoDB is that they are schema-less—there’s no schema.
That means you don’t specify a structure for the databases/tables as you do in SQL. Instead of tables and rows in
SQL, MongoDB has collections and documents. So, let’s see how you work with collections in MongoDB.

Using collections in MongoDB

In SQL, you have tables that have a well-defined structure with columns and specified data types. You insert
data into tables as records. Every record you insert should have values (including null values) for every column
defined on the table.

In contrast, NoSQL has collections instead of tables. These collections don’t have any structure, and you insert
data, as documents, into the collection. That means that one document can be completely different from another
document. Let’s create a collection called Employee and add a document to it.
35

Before you could create a collection, remember that you add data to documents in JSON format. So, the
command to insert one document to our database will look like this:

Copy

db.Employee.insert(

"Employeename" : "Chris",

"EmployeeDepartment" : "Sales"

If the insertion is successful it will return WriteResult({ “nInserted” : 1 }):

First, switch to the database to add values using the ‘use’ command. Then use db.Employee.insert command to
add a document to the database:

Db refers to the currently connected database.

Employee is the newly created collection on the company database.

A significant issue you’ll notice in this query is we haven’t set a primary key. MongoDB automatically creates a
primary key field called _id and sets a default value to it. To see this, let’s view the collection we just created.
Run the following command to access our collection in JSON format.

Copy

db.Employee.find().forEach(printjson)

It will print the following output:


36

In MongoDB, you cannot set an arbitrary field to the primary key. However, you can change the value of the
default primary key. Let’s add another document while giving value for _id as well.

Copy

db.Employee.insert(

"_id" : 1,

"EmployeeName" : "Mark",

"EmployeeDepartment" : "Marketing"

Great. Now we know how to use the primary key as well. Let’s get back to our main topic. Have we created our
database now? Run the following command again to find it out.

Copy

show dbs

Now you can see the database ‘company’ is listed in the result: it worked!

Removing a database
37

It’s not good to leave this meaningless database on your server. So, let’s remove it as it is a good chance for us
to learn how to drop a database. To drop any database you want, first, you have to connect with it using the use
keyword.

Copy

use Company

Next, type db.dropDatabase() to remove the database from your server.

Run the show dbs command again to verify it.

Using MongoDB Compass

That should be the end of our tutorial—we created and removed a Mongo database. However, I want to talk
about one more thing. Although the Mongo shell is a great tool for working with MongoDB servers, many
people find it difficult, especially in a production environment.

That’s why I encourage you to get familiar with a MongoDB Compass tool, a great GUI to work with
MongoDB. Here, I will show you how to create a database in Compass GUI. You can download the Compass
IDE for any operating system. Again, the installation process is very straightforward.

Now open the application and create a connection with the MySQL server that we installed earlier.
38

Go to ‘Fill in connection fields individually.’ It will take you to the following screen. If you use the default
values when installing MongoDB, all you have to do is click the CONNECT button.
39

Now you can see a list of databases available on your MongoDB server.
40

Click the create database button to create a new database. Then, give a database name and a collection name:
41

Unlike the Mongo shell, Compass will create a database even without adding any data:

We can verify it with the Mongo shell as well:


42

Result: The create database using MongoDb Executed successful


43

Experiment no:7 Creating XML DOUMENT and DTD

AIM

To write a Program Create a xml document and DTD

Program

Creating xml document


<html>
<body>

<p id="demo"></p>

<script>
var text, parser, xmlDoc;

text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";

parser = new DOMParser();


xmlDoc = parser.parseFromString(text,"text/xml");

document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>

</body>
</html>

Output
Everyday Italian

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

<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
44

]>

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>

Output
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>Writer: Donald Duck. Copyright: W3Schools.</footer>
</note>

Result: The Program In XML Document Executed successfully.


45

Experiment no:8 USING A RELATIONAL DATABASE TO STORE THE XML


DOCUMENT AS TEXT

AIM

To using a relational database to store the xml document as text.

Procedure

A common problem with XML documents is how to


persist them. Storing them in a relational database is often the
most logical choice because relational databases are so
prevalent.

It’s not a simple matter of inserting the XML


document into the database; there may be additional considerations.
Let’s look at some techniques you can use to store XML documents in
relational databases.

Document table

The simplest and easiest technique is to create


a table within the database that has a single large text field
where you can store the XML data. Depending on the specific
database and the specific XML documents, this field might be a
binary large object (BLOB). Some databases require you to store
large amounts of data as a BLOB rather than text.

The advantages of this technique are that it’s


extremely simple to dump the data into the table and equally simple
to extract it back out. There are no keys to manage for this
table.

Some major drawbacks are that you probably


won’t be able to do any useful text searching, and you may have
difficulties locating a specific document since there’s nothing to
identify a unique document within the table.

Keyed table

The next most complex solution is to use a


keyed table. This is very similar to the document table approach,
but this time your table has two fields: a unique key and the XML
document. With this technique, you retain much of the simplicity of
46

storing and retrieving whole XML documents. You also introduce a


small amount of complexity with managing the unique keys.

A common approach to creating unique keys is to


use an MD5 checksum on the XML document. Keep in mind that this
approach is insufficient if you are going to have duplicate XML
documents in your table. In that case, you may add additional key
fields that can be used to uniquely identify the document.

Like the document table, the keyed table is


easy to implement. The additional overhead of using the keys is not
significant and it solves the problem of finding specific documents
within the table. However, like the document table, you will still
not be able to perform any useful text searches.

Finite discrete tables

This technique is more complex, but it also


gives you more flexibility. With finite discrete tables, you create
a set of tables that will store a finite set of discrete XML
information. What does that mean? Well, here’s an example.

Imagine you have an order document. At the root


of the document is the Order element, which contains
CustomerInfo, ItemInfo, and ShippingInfo elements. Within the
database, you create an OrderDoc table that has an ID field, a
CustomerInfoId field, an ItemInfoId field, and a ShippingInfoId
field. Then, you also create a CustomerInfo table, an ItemInfo
table, and a ShippingInfo table.

These tables have their respective ID fields


along with information about the customer, the items, and the
shipping data related to the order. Within this table, there may be
additional levels of reference. For example, the CustomerInfo table
might contain an AddressInfo field, which references an entry from
the AddressInfo table.

Advantages and disadvantages

The advantage of this approach is that it


allows you to more closely model the tables to the XML data. This
allows you to perform more sophisticated queries against the data.

It also makes the data more available, since you don’t need an XML
parser to read the information.
47

The downside is that this technique requires a


lot more effort to develop and maintain. It means that every
document has to be parsed out into discrete components and then
stored in the database. If that process is not carefully managed,
you could end up with some serious data integrity issues. It also
means that when extracting an XML document from the database, you
have to assemble the discrete components.

Result: To using a relational database to store the xml document as text study sucessfully.
48

EXPERIMENT NO:9 VIEWS

AIM:

To create and drop View on the given table.

THEORY

A view is the tailored presentation of data contained in one or more table and can also be said as
restricted view to the data‟s in the tables. A view is a “virtual table” or a “stored query” which takes the output
of a query and treats it as a table. The table upon which a view is created is called as base table . A view is a
logical table based on a table or another view. A view contains no data of its own but is like a window
through which data from tables can be viewed or changed. The tables on which a view is based are called base
tables. The view is stored as a SELECT statement in the data dictionary .

Advantages of a view:

Additional level of table security.

Hides data complexity.

Simplifies the usage by combining multiple tables into a single table

Creating and dropping view:

Syntax:

Create or replace view view_name AS SELECT column_name(s)

FROM table_name WHERE condition

Drop view <view name>;

Example

Create or replace view empview as select * from emp; Drop view empview;

PROCEDURE

create a table aa

`SQL> create table aa(name varchar2(20),book number(10),edition number(20),price number(20), ISBN


number(20));

describe the table aa SQL> select * from aa;

NAME BOOK EDITION PRICE ISBN

Bb 23 2001 12 23435
Cc 55 342 76 687478
dd 2 1233 123 53616578
ee 21 1111 111 12435798
49

create table qq

SQL> create table qq(name varchar2(20),book number(10),author varchar(20),publisher varchar2(20),ISBN


number(20));

describe table qq SQL> select * from qq;

NAMEBOOK AUTHOR PUBLISHER ISBN

bb 21 23 dfd 573568

cc 43 55 fg 65839

ee 44 21 dfd 1235798

oo 87 34 gfh 6358379

create a view on qq

SQL>create view ww as select book,name,publisher from qq where ISBN=573568

View created.

display the view

SQL> select * from ww;

BOOK NAMEPUBLISHER

- 21 bb dfd 7)UPDATE VIEW STATEMENT

SQL> update ww set publisher='qwa'where book=21; 1 row updated.

SQL> select * from ww; BOOK NAME PUBLISHER

21 bb qwa

SQL> create view wq as select name,ISBN,publisher from qq where book>21 View created.

SQL> select * from wq;


50

NAME ISBN PUBLISHER

cc 65839 fg

ee 1235798 dfd

oo 6358379 gfh

SQL> create view ss as select name,book from aa union select name,book from qq;

View created.

SQL> select * from ss;

NAME BOOK

bb 21

bb 23

cc 43

cc 55

dd 2

ee 21

ee 44

oo 87

8 rows selected.
51

Problems

1)Create the following table and insert rows Table:Hosp_doc

Column name Data type and size

Doc_code Varchar2(4)

Doc_name Varchar2(4)

Specialization Varchar2(4)

Department Varchar2(4)

Date_of_join Date

Exper Number(2)

create a view vw_doctor on Hosp_doc table

create another view that contains doctor codes and doctor names of ‘orthology’ department

delete the view vw_doctor

Result

Thus the view creation commands are executed successfully


52

EXPERIMENT NO: 10 TRIGGER


AIM

Create a Trigger for EMP table it will update another table SALARY while inserting values

PROCEDURE

step 1: start

step 2: initialize the trigger with specific table id.

step 3:specify the operations (update, delete, insert) for which the trigger has to be executed.

step 4: execute the trigger procedure for both before and after sequences step 5: carryout the operation on the
table to check for trigger execution. step 6: stop

PROGRAM

sql> create table emp(iname varchar2(10),iid number(5),salary number(10)); table created.

sql> create table sal(iname varchar2(10),totalemp number(5),totalsal number(10)); table created.

sql> create or replace trigger emptrigr after insert on emp for each row

declare

a varchar2(10); begin a:=:new.iname; update sal set

totalsal=totalsal+:new.salary,totalemp=totalemp+1 where iname=a;

end;

/trigger created.

sql> insert into emp values('vec',100,1000); 1 row created.

sql> insert into sal values('vec',0,0); 1 row created.

sql> insert into sal values('srm',0,0); 1 row created.

sql> select * from sal;

iname totalemp totalsal

vec 1 1000

srm 0 0
53

sql> insert into emp values('srm',200,3000); 1 row created.

sql> select * from sal;

iname totalemp totalsal

Vec 1 1000

srm 1 3000

sql> insert into emp values('vec',100,5000); 1 row created.

sql> select * from sal; iname totalemp totalsal

vec 2 6000

srm 1 3000

sql> insert into emp values('vec',100,2000); 1 row created.

sql> select * from sal; iname totalemp totalsal

vec 3 8000

srm 1 3000

sql> insert into emp values('srm',200,8000);

1 row created.

sql> select * from sal; iname totalemp totalsal

Vec 3 8000

Srm 2 11000
54

Problems

Write a trigger that stores the details of students changing their program from CT to CHM.

Write an update trigger on CLIENT_MASTER table.The system should keep track of the records that are being
updated.The old values of the updated record should be added in the AUDIT_TRAIL table

Column name Data type size

Client_no Varchar2 6

name Varchar2 20

Bal_due Number 10,2

Operation Varchar2 8

userid Varchar2 20

olddate date

RESULT:

The trigger procedure has been executed successfully for both before and after sequences.
55

You might also like